CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-six

Python 2 and 3 compatibility utilities

Pending
Overview
Eval results
Files

execution.mddocs/

Execution and Exception Utilities

Utilities for code execution, exception handling, and print functionality that work across Python versions. These functions provide unified interfaces for executing code, handling exceptions, and printing output that work identically on Python 2 and 3.

Capabilities

Code Execution

Function for executing Python code with proper namespace handling across versions.

def exec_(_code_: str | CodeType, _globs_: dict | None = None, _locs_: dict | None = None) -> None
    """Execute code in the given namespaces."""

Parameters:

  • _code_: String containing Python code or compiled code object
  • _globs_: Global namespace dictionary (defaults to caller's globals)
  • _locs_: Local namespace dictionary (defaults to caller's locals)

Usage Examples:

import six

# Execute code string
code = """
x = 10
y = 20
result = x + y
"""
namespace = {}
six.exec_(code, namespace)
print(namespace['result'])  # 30

# Execute with specific globals and locals
global_vars = {'math': __import__('math')}
local_vars = {}
six.exec_("result = math.pi * 2", global_vars, local_vars)
print(local_vars['result'])  # 6.283185307179586

# Execute compiled code
compiled_code = compile("print('Hello from exec')", '<string>', 'exec')
six.exec_(compiled_code)

Exception Handling

Functions for raising and reraising exceptions with proper traceback handling.

def reraise(tp: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None = None) -> None
    """Reraise an exception with its original traceback."""

def raise_from(value: BaseException, from_value: BaseException | None) -> None
    """Raise exception from another exception (Python 3 syntax)."""

Usage Examples:

import six
import sys

# Reraise exception with original traceback
def handle_error():
    try:
        # Some operation that might fail
        raise ValueError("Original error")
    except Exception:
        exc_info = sys.exc_info()
        # Do some logging or cleanup
        print("Handling error...")
        # Reraise with original traceback
        six.reraise(*exc_info)

# Exception chaining (Python 3 style)
def process_data(data):
    try:
        return int(data)
    except ValueError as e:
        new_error = RuntimeError("Failed to process data")
        six.raise_from(new_error, e)  # Chain exceptions

# Usage
try:
    process_data("invalid")
except RuntimeError as e:
    print(f"Error: {e}")
    print(f"Caused by: {e.__cause__}")  # Original ValueError

Print Function

Print function with Python 3 semantics that works on both Python versions.

def print_(*args, **kwargs) -> None
    """Print function with Python 3 semantics."""

Keyword Arguments:

  • sep: String inserted between values (default: ' ')
  • end: String appended after the last value (default: '\n')
  • file: File object to write to (default: sys.stdout)
  • flush: Whether to forcibly flush the stream (default: False)

Usage Examples:

import six
import sys

# Basic printing with custom separator
six.print_("A", "B", "C", sep="-")  # A-B-C

# Custom end character
six.print_("Loading", end="")
six.print_(".", end="")
six.print_(".", end="")
six.print_(".")  # Loading...

# Print to different file
with open("output.txt", "w") as f:
    six.print_("Hello, file!", file=f)

# Print to stderr
six.print_("Error message", file=sys.stderr)

# Force flushing (useful for progress indicators)
for i in range(5):
    six.print_(f"Processing {i}", end=" ", flush=True)
    time.sleep(1)
six.print_()  # Final newline

Common Usage Patterns

import six
import sys
import traceback

# Dynamic code execution with error handling
def safe_exec(code_string, context=None):
    """Safely execute code with proper error handling."""
    if context is None:
        context = {}
    
    try:
        six.exec_(code_string, context)
        return context
    except Exception as e:
        six.print_(f"Execution failed: {e}", file=sys.stderr)
        traceback.print_exc()
        return None

# Custom exception handling with reraise
class DataProcessor:
    def __init__(self):
        self.debug = True
    
    def process(self, data):
        try:
            return self._internal_process(data)
        except Exception:
            if self.debug:
                six.print_("Debug: Processing failed for data:", data, file=sys.stderr)
            
            # Log the error and reraise with original traceback
            exc_info = sys.exc_info()
            self._log_error(*exc_info)
            six.reraise(*exc_info)
    
    def _internal_process(self, data):
        # Simulate some processing that might fail
        if not data:
            raise ValueError("Empty data provided")
        return data.upper()
    
    def _log_error(self, exc_type, exc_value, exc_tb):
        six.print_(f"Error logged: {exc_type.__name__}: {exc_value}", 
                  file=sys.stderr)

# Exception chaining for better error context
def nested_operation():
    """Example of nested operations with exception chaining."""
    
    def parse_config(config_str):
        try:
            return eval(config_str)  # Dangerous but for example
        except SyntaxError as e:
            parse_error = ValueError(f"Invalid configuration format")
            six.raise_from(parse_error, e)
    
    def load_config(filename):
        try:
            with open(filename) as f:
                return parse_config(f.read())
        except (IOError, OSError) as e:
            load_error = RuntimeError(f"Failed to load config from {filename}")
            six.raise_from(load_error, e)
        except ValueError as e:
            # Re-raise parse errors with additional context
            config_error = RuntimeError(f"Configuration error in {filename}")
            six.raise_from(config_error, e)
    
    return load_config("config.py")

# Advanced printing with formatting
def progress_printer():
    """Example of using print_ for progress indication."""
    
    def print_progress(current, total, message="Processing"):
        percent = (current / total) * 100
        bar_length = 20
        filled_length = int(bar_length * current // total)
        bar = '█' * filled_length + '-' * (bar_length - filled_length)
        
        six.print_(f'\r{message}: |{bar}| {percent:.1f}%', 
                  end='', flush=True)
        
        if current == total:
            six.print_()  # Final newline
    
    # Simulate progress
    import time
    total_items = 10
    for i in range(total_items + 1):
        print_progress(i, total_items)
        time.sleep(0.1)

# Template execution system
class TemplateEngine:
    """Simple template engine using exec_."""
    
    def __init__(self):
        self.globals = {
            'six': six,
            '__builtins__': __builtins__
        }
    
    def render(self, template, context=None):
        if context is None:
            context = {}
        
        # Create isolated namespace
        namespace = self.globals.copy()
        namespace.update(context)
        
        # Template processing code
        template_code = f"""
output = []
def write(text):
    output.append(str(text))

{template}

result = ''.join(output)
"""
        
        try:
            six.exec_(template_code, namespace)
            return namespace['result']
        except Exception as e:
            error_msg = f"Template rendering failed: {e}"
            six.print_(error_msg, file=sys.stderr)
            raise RuntimeError(error_msg) from e

# Usage example
template = '''
write("Hello, ")
write(name)
write("! You have ")
write(count)
write(" messages.")
'''

engine = TemplateEngine()
result = engine.render(template, {'name': 'Alice', 'count': 5})
six.print_(result)  # Hello, Alice! You have 5 messages.

Install with Tessl CLI

npx tessl i tessl/pypi-six

docs

execution.md

index.md

iterator-dict.md

metaclass.md

moves.md

string-bytes.md

testing.md

version-detection.md

tile.json