CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-stack-data

Extract data from python stack frames and tracebacks for informative displays

Overview
Eval results
Files

formatting.mddocs/

Text Formatting

Comprehensive text formatting system for displaying stack traces and frame information with syntax highlighting, variable display, customizable output options, and support for both plain text and HTML output formats.

Capabilities

Formatter Configuration

Central formatting class that provides customizable text output for stack traces, exceptions, and frame information with extensive styling and display options.

class Formatter:
    def __init__(self, *,
                 options: Optional[Options] = None,
                 pygmented: bool = False,
                 show_executing_node: bool = True,
                 pygments_formatter_cls = None,
                 pygments_formatter_kwargs: Optional[dict] = None,
                 pygments_style: str = "monokai",
                 executing_node_modifier: str = "bg:#005080",
                 executing_node_underline: str = "^",
                 current_line_indicator: str = "-->",
                 line_gap_string: str = "(...)",
                 line_number_gap_string: str = ":",
                 line_number_format_string: str = "{:4} | ",
                 show_variables: bool = False,
                 use_code_qualname: bool = True,
                 show_linenos: bool = True,
                 strip_leading_indent: bool = True,
                 html: bool = False,
                 chain: bool = True,
                 collapse_repeated_frames: bool = True):
        """
        Create Formatter with extensive customization options.
        
        Args:
            options: Stack data options for frame analysis
            pygmented: Whether to use syntax highlighting
            show_executing_node: Whether to highlight executing node
            pygments_formatter_cls: Custom Pygments formatter class
            pygments_formatter_kwargs: Arguments for Pygments formatter
            pygments_style: Pygments style name for syntax highlighting
            executing_node_modifier: CSS-like modifier for executing node highlighting
            executing_node_underline: Character for underlining executing node
            current_line_indicator: Indicator string for current line
            line_gap_string: String to show for line gaps
            line_number_gap_string: String for line number gaps
            line_number_format_string: Format string for line numbers
            show_variables: Whether to show variable values
            use_code_qualname: Whether to use qualified names for code objects
            show_linenos: Whether to show line numbers
            strip_leading_indent: Whether to strip leading indentation
            html: Whether to generate HTML output
            chain: Whether to chain exception causes and contexts
            collapse_repeated_frames: Whether to collapse repeated frames
        """

Exception Formatting

High-level functions for formatting and displaying exceptions with enhanced context, variable information, and customizable styling.

def print_exception(self, e: Optional[BaseException] = None, *, 
                   file = None) -> None:
    """
    Print formatted exception with enhanced display.
    
    Args:
        e: Exception to format (uses sys.exc_info() if None)
        file: File object to write to (uses sys.stderr if None)
    """

def format_exception(self, e: Optional[BaseException] = None) -> Iterable[str]:
    """
    Format exception as iterable of strings.
    
    Args:
        e: Exception to format (uses sys.exc_info() if None)
        
    Yields:
        Formatted strings for each part of the exception display
    """

def set_hook(self) -> None:
    """Install this formatter as sys.excepthook for automatic exception formatting."""

Stack Formatting

Functions for formatting and displaying stack traces with detailed frame information, source context, and variable inspection.

def print_stack(self, frame_or_tb: Optional[Union[FrameType, TracebackType]] = None, 
               *, file = None) -> None:
    """
    Print formatted stack trace.
    
    Args:
        frame_or_tb: Frame or traceback to start from (uses current frame if None)
        file: File object to write to (uses sys.stderr if None)
    """

def format_stack(self, frame_or_tb: Optional[Union[FrameType, TracebackType]] = None) -> Iterable[str]:
    """
    Format stack trace as iterable of strings.
    
    Args:
        frame_or_tb: Frame or traceback to start from (uses current frame if None)
        
    Yields:
        Formatted strings for each part of the stack display
    """

def format_stack_data(self, stack: Iterable[Union[FrameInfo, RepeatedFrames]]) -> Iterable[str]:
    """
    Format stack data objects as strings.
    
    Args:
        stack: Iterable of FrameInfo and RepeatedFrames objects
        
    Yields:
        Formatted strings for each stack element
    """

Frame Formatting

Detailed formatting functions for individual stack frames, including headers, source lines, and variable display.

def format_frame(self, frame: Union[FrameInfo, FrameType, TracebackType]) -> Iterable[str]:
    """
    Format individual frame with source code and context.
    
    Args:
        frame: Frame object to format (FrameInfo, FrameType, or TracebackType)
        
    Yields:
        Formatted strings for frame display
    """

def format_frame_header(self, frame_info: FrameInfo) -> str:
    """
    Format frame header with file and function information.
    
    Args:
        frame_info: FrameInfo object
        
    Returns:
        Formatted header string
    """

def format_repeated_frames(self, repeated_frames: RepeatedFrames) -> str:
    """
    Format repeated frames with count and description.
    
    Args:
        repeated_frames: RepeatedFrames object
        
    Returns:
        Formatted string describing repeated frames
    """

Line Formatting

Functions for formatting individual source code lines with line numbers, indicators, and syntax highlighting.

def format_line(self, line: Line) -> str:
    """
    Format individual source code line.
    
    Args:
        line: Line object to format
        
    Returns:
        Formatted line string with line number and indicators
    """

def format_blank_lines_linenumbers(self, blank_line: BlankLineRange) -> str:
    """
    Format line numbers for blank line ranges.
    
    Args:
        blank_line: BlankLineRange object
        
    Returns:
        Formatted line number string for blank lines
    """

def print_lines(self, lines: Iterable[str], *, file = None) -> None:
    """
    Print formatted lines to file.
    
    Args:
        lines: Iterable of formatted strings
        file: File object to write to (uses sys.stdout if None)
    """

Variable Formatting

Functions for formatting variable information including names, values, and type information.

def format_variables(self, frame_info: FrameInfo) -> Iterable[str]:
    """
    Format all variables in frame.
    
    Args:
        frame_info: FrameInfo object containing variables
        
    Yields:
        Formatted strings for each variable
    """

def format_variable(self, var: Variable) -> str:
    """
    Format individual variable with name and value.
    
    Args:
        var: Variable object to format
        
    Returns:
        Formatted string showing variable name and value
    """

def format_variable_value(self, value: Any) -> str:
    """
    Format variable value with appropriate representation.
    
    Args:
        value: Variable value to format
        
    Returns:
        Formatted string representation of the value
    """

Usage Examples

Basic Exception Formatting

from stack_data import Formatter

# Create formatter with default settings
formatter = Formatter()

# Install as exception hook
formatter.set_hook()

# Now all exceptions will use enhanced formatting
try:
    result = 1 / 0
except Exception as e:
    # This will use the enhanced formatter
    raise

# Or format manually
try:
    result = 1 / 0  
except Exception as e:
    formatter.print_exception(e)

Customized Stack Display

from stack_data import Formatter, Options, BlankLines

# Create formatter with custom options
formatter = Formatter(
    pygmented=True,  # Enable syntax highlighting
    show_variables=True,  # Show variable values
    show_executing_node=True,  # Highlight current node
    current_line_indicator=">>>",  # Custom line indicator
    pygments_style="github-dark",  # Dark theme
    show_linenos=True,  # Show line numbers
    options=Options(
        before=5,  # More context before
        after=3,   # More context after
        blank_lines=BlankLines.SINGLE  # Collapse blank lines
    )
)

# Print current stack
formatter.print_stack()

HTML Output

from stack_data import Formatter

# Create HTML formatter
html_formatter = Formatter(
    html=True,  # Generate HTML output
    pygmented=True,  # Syntax highlighting in HTML
    show_variables=True,  # Include variables
    pygments_style="monokai"  # Dark style for HTML
)

# Get HTML output as strings
try:
    result = 1 / 0
except Exception as e:
    html_lines = list(html_formatter.format_exception(e))
    html_output = ''.join(html_lines)
    print(html_output)

Variable Display Control

from stack_data import Formatter

# Formatter focused on variable display
var_formatter = Formatter(
    show_variables=True,
    show_executing_node=False,  # Focus on variables, not execution
    show_linenos=False,  # Cleaner display
    strip_leading_indent=True,  # Remove indentation
    current_line_indicator="*"  # Subtle indicator
)

import inspect
frame = inspect.currentframe()

# Format just the current frame
for line in var_formatter.format_frame(frame):
    print(line, end='')

Custom Styling

from stack_data import Formatter

# Formatter with custom styling
styled_formatter = Formatter(
    pygmented=True,
    executing_node_modifier="bg:#ff0000",  # Red background for current node
    executing_node_underline="^",  # Underline character
    line_gap_string="[... skipped lines ...]",  # Custom gap indicator
    line_number_format_string="{:6d} | ",  # Wider line numbers
    pygments_style="material"  # Material design colors
)

styled_formatter.print_stack()

Exception Chaining

from stack_data import Formatter

# Formatter with exception chaining
chain_formatter = Formatter(
    chain=True,  # Show exception causes and contexts
    show_variables=True,  # Show variables in all frames
    collapse_repeated_frames=True  # Collapse recursive calls
)

def outer():
    try:
        inner()
    except ValueError as e:
        raise RuntimeError("Outer error") from e

def inner():
    raise ValueError("Inner error")

try:
    outer()
except Exception as e:
    chain_formatter.print_exception(e)
    # Will show both ValueError and RuntimeError with full context

Minimal Output

from stack_data import Formatter

# Minimal formatter for clean output
minimal_formatter = Formatter(
    pygmented=False,  # No syntax highlighting
    show_variables=False,  # No variables
    show_executing_node=False,  # No highlighting
    show_linenos=False,  # No line numbers
    current_line_indicator="",  # No indicator
    strip_leading_indent=True,  # Clean indentation
    collapse_repeated_frames=True  # Collapse recursion
)

minimal_formatter.print_stack()

Install with Tessl CLI

npx tessl i tessl/pypi-stack-data

docs

formatting.md

frame-analysis.md

index.md

serialization.md

tile.json