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

global-hooks.mddocs/

Global Exception Hooks

System-level integration that replaces Python's default exception handling with enhanced traceback display. Supports both standard Python environments and IPython/Jupyter notebooks with automatic environment detection and appropriate hook installation.

Capabilities

Python Global Hook Installation

Install enhanced exception handling for standard Python environments using sys.excepthook.

def global_print_exc(fmt: Optional[Format] = None) -> None:
    """
    Install global exception hook for standard Python environments.
    
    Replaces sys.excepthook to display enhanced tracebacks with variables
    for all unhandled exceptions.
    
    Parameters:
    - fmt: Format configuration (uses default_format if None)
    
    Usage:
    global_print_exc()  # All unhandled exceptions now show variables
    """

IPython/Jupyter Hook Installation

Install enhanced exception handling specifically for IPython and Jupyter notebook environments.

def global_print_exc_in_ipython(fmt: Optional[Format] = None) -> None:
    """
    Install global exception hook for IPython/Jupyter environments.
    
    Replaces IPython.core.interactiveshell.InteractiveShell.showtraceback
    to display enhanced tracebacks with variables.
    
    Parameters:
    - fmt: Format configuration (uses default_format if None)
    
    Raises:
    ValueError: If IPython is not available
    
    Usage:
    global_print_exc_in_ipython()  # All exceptions in IPython show variables
    """

Environment Detection

Functions to detect and handle different Python environments automatically.

def in_ipython() -> bool:
    """
    Detect if code is running in IPython/Jupyter environment.
    
    Returns:
    True if in IPython/Jupyter, False if in standard Python
    """

def is_ipython_global(name: str, type_: Type, filename: str, is_global: bool) -> bool:
    """
    Filter function to identify IPython-specific global variables.
    
    Identifies IPython built-in variables that should typically be hidden
    from traceback display (In, Out, get_ipython, exit, quit, _* variables).
    
    Parameters:
    - name: Variable name
    - type_: Variable type
    - filename: Source file name
    - is_global: Whether variable is global
    
    Returns:
    True if variable is an IPython global that should be filtered
    """

Default Hook Configurations

Pre-configured hook installation functions with sensible defaults for different environments.

def default_global_print_exc() -> None:
    """
    Install global hook with default settings for standard Python.
    
    Automatically configures:
    - Hides global variables by default
    - Uses standard color scheme detection
    - Applies security-focused variable filtering
    """

def default_global_print_exc_in_ipython() -> None:
    """
    Install global hook with default settings for IPython/Jupyter.
    
    Automatically configures:
    - Hides IPython-specific global variables
    - Forces common color scheme (suitable for notebooks)
    - Filters IPython built-ins (In, Out, get_ipython, etc.)
    """

def default_global_print_exc_in_all() -> None:
    """
    Install appropriate global hook based on current environment.
    
    Automatically detects environment and calls either:
    - default_global_print_exc_in_ipython() if in IPython/Jupyter
    - default_global_print_exc() if in standard Python
    """

Usage Examples

Basic Global Hook Installation

from traceback_with_variables import global_print_exc

# Install global hook
global_print_exc()

# Now all unhandled exceptions show variables automatically
def problematic_function():
    x = 42
    y = "hello"
    return x / 0  # This will show enhanced traceback

problematic_function()  # Enhanced traceback displayed automatically

Custom Format with Global Hook

from traceback_with_variables import global_print_exc, Format, ColorSchemes

# Create custom format
custom_fmt = Format(
    max_value_str_len=300,
    color_scheme=ColorSchemes.synthwave,
    before=1,
    after=1
)

# Install with custom format
global_print_exc(fmt=custom_fmt)

# All exceptions now use custom formatting
data = {"config": {"database": {"host": "localhost"}}}
connection = data["config"]["database"]["port"]  # Enhanced output with custom format

IPython/Jupyter Integration

from traceback_with_variables import global_print_exc_in_ipython, Format

# For Jupyter notebooks - install IPython-specific hook
try:
    global_print_exc_in_ipython()
    print("Enhanced tracebacks enabled for Jupyter!")
except ValueError as e:
    print(f"Not in IPython environment: {e}")

# Now all cell exceptions show variables with IPython-appropriate formatting
notebook_data = {"results": [1, 2, 3, 4, 5]}
analysis = notebook_data["missing_data"]  # Enhanced traceback in notebook

Automatic Environment Detection

from traceback_with_variables import default_global_print_exc_in_all

# Automatically detect environment and install appropriate hook
default_global_print_exc_in_all()

# Works correctly in both standard Python and IPython/Jupyter
experimental_data = {"trials": 100, "success_rate": 0.85}
critical_value = experimental_data["failure_rate"]  # Auto-formatted for environment

Auto-activation Imports

The simplest way to enable enhanced tracebacks globally:

# Auto-activate in any environment (most convenient)
import traceback_with_variables.activate_by_import

# Auto-activate only in standard Python (not Jupyter)
import traceback_with_variables.activate_in_python_by_import

# Auto-activate only in Jupyter/IPython
import traceback_with_variables.activate_in_ipython_by_import

# Ultra-short alias for interactive use
import traceback_with_variables.a  # Same as activate_by_import

Production-Safe Global Hooks

from traceback_with_variables import global_print_exc, Format, hide, skip
import logging
import os

# Create production-safe format
production_fmt = Format(
    # Hide sensitive information
    custom_var_printers=[
        (r'.*(?i:password|secret|token|key|api).*', hide),
        (lambda name, type_, filename, is_global: 
         name.startswith('ENV_'), skip),
    ],
    
    # Limit verbosity for production logs
    max_value_str_len=200,
    objects_details=1,
    
    # No colors for log files
    color_scheme=None
)

# Only install in development/debugging mode
if os.getenv('DEBUG', '').lower() in ('1', 'true', 'yes'):
    global_print_exc(fmt=production_fmt)
    print("Enhanced tracebacks enabled for debugging")
else:
    print("Running in production mode - standard tracebacks")

Temporary Global Hook

from traceback_with_variables import global_print_exc
import sys

# Save original exception hook
original_excepthook = sys.excepthook

# Install enhanced hook temporarily
global_print_exc()

try:
    # Code that might have exceptions
    debug_session_data = {"session_id": "abc123", "user": "developer"}
    process_data = debug_session_data["nonexistent_key"]
    
except Exception:
    pass  # Exception shows with variables

finally:
    # Restore original hook
    sys.excepthook = original_excepthook
    print("Restored original exception handling")

Environment-Specific Configuration

from traceback_with_variables import (
    in_ipython, 
    global_print_exc, 
    global_print_exc_in_ipython,
    Format, 
    ColorSchemes
)

# Different configurations for different environments
if in_ipython():
    # Jupyter/IPython: colorful output suitable for notebooks
    jupyter_fmt = Format(
        color_scheme=ColorSchemes.nice,
        max_value_str_len=400,
        before=1,
        after=0
    )
    global_print_exc_in_ipython(fmt=jupyter_fmt)
    print("Enhanced Jupyter tracebacks enabled")
    
else:
    # Standard Python: more compact output for terminal
    terminal_fmt = Format(
        color_scheme=ColorSchemes.common,
        max_value_str_len=200,
        objects_details=1
    )
    global_print_exc(fmt=terminal_fmt)
    print("Enhanced terminal tracebacks enabled")

# Test the configuration
test_data = {"environment": "detected", "config": "applied"}
result = test_data["missing"]  # Will use appropriate formatting

Module Alias Creation

from traceback_with_variables.tb_alias import create_tb_alias, rm_tb_alias

# Create filesystem alias for shorter imports
try:
    create_tb_alias()
    print("Created 'tb' alias - you can now use: import tb")
    
    # Now you can use: import tb instead of import traceback_with_variables
    # import tb.activate_by_import  # Same as traceback_with_variables.activate_by_import
    
except ValueError as e:
    print(f"Could not create alias: {e}")

# Remove alias when done
try:
    rm_tb_alias()
    print("Removed 'tb' alias")
except ValueError as e:
    print(f"Could not remove alias: {e}")

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