or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

formatting.mdframe-analysis.mdindex.mdserialization.md
tile.json

tessl/pypi-stack-data

Extract data from python stack frames and tracebacks for informative displays

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/stack-data@0.6.x

To install, run

npx @tessl/cli install tessl/pypi-stack-data@0.6.0

index.mddocs/

Stack Data

A comprehensive Python library for extracting and displaying data from Python stack frames and tracebacks in an informative, customizable way. Stack Data provides enhanced debugging capabilities with variable inspection, syntax highlighting, configurable formatting, and structured data export, serving as the foundation for better debugging experiences in educational tools like futurecoder and IPython.

Package Information

  • Package Name: stack-data
  • Language: Python
  • Installation: pip install stack-data
  • Dependencies: executing>=1.2.0, asttokens>=2.1.0, pure_eval

Core Imports

import stack_data

Common imports for core functionality:

from stack_data import FrameInfo, Options, Formatter, Serializer

For specific classes and functions:

from stack_data import (
    Source, FrameInfo, Options, Variable, Line, 
    markers_from_ranges, style_with_executing_node,
    Formatter, Serializer, BlankLines, RangeInLine, 
    MarkerInLine, LINE_GAP, RepeatedFrames, BlankLineRange
)

Basic Usage

import inspect
from stack_data import FrameInfo, Formatter

# Get current frame and create FrameInfo
frame = inspect.currentframe()
frame_info = FrameInfo(frame)

# Display lines with context
for line in frame_info.lines:
    if hasattr(line, 'text'):
        print(f"{line.lineno}: {line.text}")

# Use Formatter for enhanced display
formatter = Formatter(show_variables=True, pygmented=True)
formatter.print_stack()

# Exception handling with enhanced display
try:
    # Some code that might raise an exception
    result = 1 / 0
except Exception as e:
    formatter.print_exception(e)

Architecture

Stack Data provides a layered architecture for stack frame analysis:

  • FrameInfo: Central class that extracts rich information from stack frames, including source code context, variable values, and execution state
  • Source: Enhanced source code representation with AST parsing, tokenization, and metadata
  • Options: Configuration system for controlling display behavior, context size, and formatting preferences
  • Variable: Expression evaluation system using pure_eval for safe variable inspection
  • Formatters: Multiple output formats (text display, HTML, structured data) for different use cases

This design enables flexible stack trace analysis and display, supporting everything from simple debugging output to sophisticated educational tools and development environments.

Capabilities

Stack Frame Analysis

Core functionality for analyzing Python stack frames and extracting detailed information including source code context, variable values, and execution state.

class FrameInfo:
    def __init__(self, frame_or_tb, options=None): ...
    @classmethod
    def stack_data(cls, frame_or_tb, options=None, *, collapse_repeated_frames=True): ...

class Options:
    def __init__(self, *, before=3, after=1, include_signature=False, 
                 max_lines_per_piece=6, pygments_formatter=None, 
                 blank_lines=BlankLines.HIDDEN): ...

class Source:
    @property
    def pieces(self): ...
    @property  
    def tokens_by_lineno(self): ...

Stack Frame Analysis

Text Formatting

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

class Formatter:
    def __init__(self, *, options=None, pygmented=False, show_executing_node=True,
                 show_variables=False, show_linenos=True, html=False, 
                 chain=True, collapse_repeated_frames=True): ...
    
    def print_exception(self, e=None, *, file=None): ...
    def print_stack(self, frame_or_tb=None, *, file=None): ...
    def format_exception(self, e=None): ...
    def format_stack(self, frame_or_tb=None): ...

Text Formatting

Data Serialization

Structured data export functionality for converting stack traces and frame information into dictionaries and lists suitable for JSON serialization and programmatic processing.

class Serializer:
    def __init__(self, *, options=None, pygmented=False, show_executing_node=True,
                 use_code_qualname=True, strip_leading_indent=True, html=False,
                 chain=True, collapse_repeated_frames=True, show_variables=False): ...
    
    def format_exception(self, e=None): ...
    def format_stack(self, frame_or_tb=None): ...
    def format_frame(self, frame): ...

Data Serialization

Types

from typing import NamedTuple, Any, Sequence, List, Union, Optional, Mapping
from types import FrameType, TracebackType
from asttokens.util import Token
import ast
from enum import Enum

class Variable(NamedTuple):
    name: str
    nodes: Sequence[ast.AST] 
    value: Any

class RangeInLine(NamedTuple):
    start: int
    end: int
    data: Any

class MarkerInLine(NamedTuple):
    position: int
    is_start: bool
    string: str

class BlankLines(Enum):
    HIDDEN = 1
    VISIBLE = 2
    SINGLE = 3

class LineGap:
    """
    A singleton representing one or more lines of source code that were skipped.
    """
    def __repr__(self) -> str: ...

class BlankLineRange:
    def __init__(self, begin_lineno: int, end_lineno: int): ...
    begin_lineno: int
    end_lineno: int

class Line:
    def __init__(self, frame_info: 'FrameInfo', lineno: int): ...
    lineno: int
    text: str
    leading_indent: Optional[int]
    is_current: bool
    tokens: List[Token]
    
    def render(self, markers=(), *, strip_leading_indent=True, 
              pygmented=False, escape_html=False) -> str: ...
    def token_ranges(self) -> List[RangeInLine]: ...
    def variable_ranges(self) -> List[RangeInLine]: ...
    def executing_node_ranges(self) -> List[RangeInLine]: ...
    def range_from_node(self, node: ast.AST, data: Any, common_indent: int = 0) -> Optional[RangeInLine]: ...

class RepeatedFrames:
    def __init__(self, frames: List[Union[FrameType, TracebackType]], 
                 frame_keys: List): ...
    frames: List[Union[FrameType, TracebackType]]
    description: str

Constants

LINE_GAP: LineGap  # Singleton instance representing skipped lines