CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-traceback-with-variables

Adds variables to python traceback with simple, lightweight, controllable debugging capabilities.

Overview
Eval results
Files

utilities.mddocs/

Utilities and Aliases

Utility functions and module aliasing system for enhanced convenience and integration. Includes filesystem-based module aliases for shorter imports and ANSI color code utilities.

Capabilities

Module Aliasing System

Create filesystem-based aliases for shorter and more convenient module imports.

def create_alias(alias: str, module_name: str) -> None:
    """
    Create a filesystem alias for a module to enable shorter imports.
    
    Creates a symbolic link in the module's parent directory that points
    to the original module, allowing import via the shorter alias name.
    
    Parameters:
    - alias: Short name for the alias (must be valid Python identifier)
    - module_name: Full name of the module to alias
    
    Raises:
    - ValueError: If alias is empty, contains invalid characters, or conflicts
    - FileExistsError: If filesystem location is already occupied
    
    Requirements:
    - Alias must contain only ASCII lowercase letters, digits, and underscores
    - Module must exist and be importable
    - Filesystem must support symbolic links
    """

def rm_alias(alias: str) -> None:
    """
    Remove a previously created module alias.
    
    Removes the symbolic link created by create_alias, restoring the
    filesystem to its original state.
    
    Parameters:
    - alias: Name of the alias to remove
    
    Raises:
    - ValueError: If the module is not an alias (not a symbolic link)
    - ModuleNotFoundError: If the alias doesn't exist
    """

def module_name_to_path(name: str) -> Path:
    """
    Convert a module name to its filesystem path.
    
    Uses importlib to find the module's location and returns the
    appropriate path (directory for packages, file for modules).
    
    Parameters:
    - name: Module name to locate
    
    Returns:
    Path object pointing to the module's location
    
    Raises:
    ModuleNotFoundError: If the module cannot be found
    """

def module_exists(name: str) -> bool:
    """
    Check if a module exists and can be imported.
    
    Parameters:
    - name: Module name to check
    
    Returns:
    True if module exists, False otherwise
    """

Traceback-with-Variables Specific Aliases

Convenience functions for creating and managing the 'tb' alias for traceback-with-variables.

def create_tb_alias() -> None:
    """
    Create 'tb' alias for traceback-with-variables module.
    
    Allows using 'import tb' instead of 'import traceback_with_variables'
    for more convenient interactive usage.
    
    Equivalent to: create_alias('tb', 'traceback_with_variables')
    
    Raises:
    ValueError: If alias creation fails
    """

def rm_tb_alias() -> None:
    """
    Remove the 'tb' alias for traceback-with-variables.
    
    Removes the symbolic link created by create_tb_alias.
    
    Equivalent to: rm_alias('tb')
    
    Raises:
    ValueError: If alias removal fails
    """

ANSI Color Utilities

Low-level utilities for working with ANSI color codes.

def to_ansi(str_: str) -> str:
    """
    Convert a color code string to a complete ANSI escape sequence.
    
    Takes a color code (e.g., '31' for red, '32;1' for bright green)
    and wraps it in the appropriate ANSI escape sequence format.
    
    Parameters:
    - str_: ANSI color code string (e.g., '31', '32;1', '38;2;255;0;0')
    
    Returns:
    Complete ANSI escape sequence (e.g., '\033[31m') or empty string if input is empty
    
    Examples:
    - to_ansi('31') -> '\033[31m'        # Red
    - to_ansi('32;1') -> '\033[32;1m'    # Bright green
    - to_ansi('') -> ''                  # No color
    """

Usage Examples

Creating Module Aliases

from traceback_with_variables.module_alias import create_alias, rm_alias

# Create a short alias for a long module name
try:
    create_alias('np', 'numpy')
    print("Created 'np' alias for numpy")
    
    # Now you can use: import np
    # Instead of: import numpy as np
    
except ValueError as e:
    print(f"Failed to create alias: {e}")

# Remove the alias when done
try:
    rm_alias('np')
    print("Removed 'np' alias")
except ValueError as e:
    print(f"Failed to remove alias: {e}")

Traceback-with-Variables Alias

from traceback_with_variables.tb_alias import create_tb_alias, rm_tb_alias

# Create convenient 'tb' alias
try:
    create_tb_alias()
    print("Created 'tb' alias - you can now use shorter imports!")
    
    # Now you can use:
    # import tb                                    # Instead of: import traceback_with_variables
    # import tb.activate_by_import                 # Instead of: import traceback_with_variables.activate_by_import
    # from tb import print_exc, Format            # Instead of: from traceback_with_variables import print_exc, Format
    # tb.print_exc(exception)                     # Instead of: traceback_with_variables.print_exc(exception)
    
except ValueError as e:
    print(f"Could not create tb alias: {e}")

# Example usage with alias
try:
    import tb
    
    # Use the alias for enhanced tracebacks
    def test_function():
        data = {"key": "value"}
        return data["missing"]
    
    try:
        test_function()
    except Exception as e:
        tb.print_exc(e)  # Much shorter than traceback_with_variables.print_exc(e)
        
finally:
    # Clean up alias
    try:
        rm_tb_alias()
        print("Removed 'tb' alias")
    except ValueError:
        pass

Interactive Development with Aliases

from traceback_with_variables.tb_alias import create_tb_alias

# Set up for interactive session
try:
    create_tb_alias()
    
    # Ultra-convenient interactive usage
    import tb.activate_by_import  # Auto-activate enhanced tracebacks
    from tb import Format, ColorSchemes  # Import commonly used classes
    
    # Set up interactive-friendly format
    interactive_fmt = Format(
        color_scheme=ColorSchemes.nice,
        max_value_str_len=200,
        before=1,
        after=0
    )
    
    # Use throughout interactive session
    try:
        interactive_data = {"session": "active", "user": "developer"}
        result = interactive_data["nonexistent"]
    except Exception as e:
        tb.print_exc(e, fmt=interactive_fmt)
        
except ValueError as e:
    print(f"Alias setup failed: {e}")
    # Fall back to full module name
    import traceback_with_variables.activate_by_import

Module Existence Checking

from traceback_with_variables.module_alias import module_exists, module_name_to_path

# Check if modules exist before creating aliases
modules_to_alias = {
    'np': 'numpy',
    'pd': 'pandas', 
    'plt': 'matplotlib.pyplot',
    'tb': 'traceback_with_variables'
}

for alias, module_name in modules_to_alias.items():
    if module_exists(module_name):
        try:
            create_alias(alias, module_name)
            module_path = module_name_to_path(module_name)
            print(f"Created alias '{alias}' -> '{module_name}' (at {module_path})")
        except ValueError as e:
            print(f"Could not create alias '{alias}': {e}")
    else:
        print(f"Module '{module_name}' not available, skipping alias '{alias}'")

Custom ANSI Color Creation

from traceback_with_variables.color import to_ansi, ColorScheme

# Create custom colors using to_ansi utility
def create_custom_color_scheme():
    """Create a custom color scheme using ANSI utilities."""
    return ColorScheme(
        common=to_ansi('0'),           # Normal
        file_=to_ansi('34'),           # Blue  
        line_num=to_ansi('33'),        # Yellow
        func_name=to_ansi('35'),       # Magenta
        func_snippet=to_ansi('37'),    # White
        name=to_ansi('36'),            # Cyan
        value=to_ansi('32'),           # Green
        exc_class=to_ansi('31;1'),     # Bright red
        exc_text=to_ansi('31'),        # Red
        end=to_ansi('0')               # Reset
    )

# Create RGB color scheme (for terminals that support it)
def create_rgb_color_scheme():
    """Create an RGB color scheme using 24-bit color codes."""
    return ColorScheme(
        common=to_ansi('38;2;200;200;200'),      # Light gray
        file_=to_ansi('38;2;100;150;255'),       # Light blue
        line_num=to_ansi('38;2;255;200;100'),    # Orange
        func_name=to_ansi('38;2;255;100;200'),   # Pink
        func_snippet=to_ansi('38;2;150;255;150'), # Light green
        name=to_ansi('38;2;200;100;255'),        # Purple
        value=to_ansi('38;2;100;255;200'),       # Cyan
        exc_class=to_ansi('38;2;255;100;100'),   # Light red
        exc_text=to_ansi('38;2;255;150;150'),    # Lighter red
        end=to_ansi('0')                         # Reset
    )

# Use custom color schemes
from traceback_with_variables import Format, print_exc

custom_fmt = Format(color_scheme=create_custom_color_scheme())
rgb_fmt = Format(color_scheme=create_rgb_color_scheme())

try:
    test_data = {"colors": ["red", "green", "blue"]}
    missing_color = test_data["missing_colors"]
except Exception as e:
    print("=== Custom Color Scheme ===")
    print_exc(e, fmt=custom_fmt)
    
    print("\n=== RGB Color Scheme ===")
    print_exc(e, fmt=rgb_fmt)

Alias Management Utilities

from traceback_with_variables.module_alias import create_alias, rm_alias, module_exists
import os

class AliasManager:
    """Utility class for managing multiple module aliases."""
    
    def __init__(self):
        self.aliases = {}
    
    def create_alias_safe(self, alias: str, module_name: str) -> bool:
        """Safely create an alias with error handling."""
        if not module_exists(module_name):
            print(f"Module '{module_name}' not found")
            return False
            
        try:
            create_alias(alias, module_name)
            self.aliases[alias] = module_name
            print(f"Created alias: '{alias}' -> '{module_name}'")
            return True
        except ValueError as e:
            print(f"Could not create alias '{alias}': {e}")
            return False
    
    def remove_all_aliases(self):
        """Remove all created aliases."""
        for alias in list(self.aliases.keys()):
            try:
                rm_alias(alias)
                print(f"Removed alias: '{alias}'")
                del self.aliases[alias]
            except ValueError as e:
                print(f"Could not remove alias '{alias}': {e}")
    
    def list_aliases(self):
        """List all active aliases."""
        if not self.aliases:
            print("No active aliases")
        else:
            print("Active aliases:")
            for alias, module in self.aliases.items():
                print(f"  '{alias}' -> '{module}'")

# Usage
manager = AliasManager()

# Create commonly used aliases
manager.create_alias_safe('tb', 'traceback_with_variables')
manager.create_alias_safe('np', 'numpy')
manager.create_alias_safe('pd', 'pandas')

# List what was created
manager.list_aliases()

# Use the aliases
try:
    import tb
    tb.activate_by_import  # Auto-activate enhanced tracebacks
except ImportError:
    print("tb alias not available")

# Clean up when done
manager.remove_all_aliases()

Platform-Specific Alias Handling

import sys
import os
from traceback_with_variables.module_alias import create_alias, rm_alias

def create_platform_safe_alias(alias: str, module_name: str) -> bool:
    """Create alias with platform-specific error handling."""
    
    if sys.platform == 'win32':
        # Windows may not support symbolic links without admin privileges
        try:
            create_alias(alias, module_name)
            return True
        except (OSError, PermissionError) as e:
            print(f"Windows alias creation failed (may need admin rights): {e}")
            return False
    else:
        # Unix-like systems generally support symbolic links
        try:
            create_alias(alias, module_name)
            return True
        except ValueError as e:
            print(f"Unix alias creation failed: {e}")
            return False

# Platform-aware alias creation
if create_platform_safe_alias('tb', 'traceback_with_variables'):
    print("Successfully created 'tb' alias")
    
    # Use the alias
    import tb.activate_by_import
    
    # Clean up
    try:
        rm_alias('tb')
    except ValueError:
        pass
else:
    print("Using full module name instead of alias")
    import traceback_with_variables.activate_by_import

Install with Tessl CLI

npx tessl i tessl/pypi-traceback-with-variables

docs

cli-interface.md

color-system.md

configuration.md

core-formatting.md

default-hooks.md

global-hooks.md

index.md

printing.md

utilities.md

tile.json