Extract data from python stack frames and tracebacks for informative displays
npx @tessl/cli install tessl/pypi-stack-data@0.6.00
# Stack Data
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: stack-data
7
- **Language**: Python
8
- **Installation**: `pip install stack-data`
9
- **Dependencies**: executing>=1.2.0, asttokens>=2.1.0, pure_eval
10
11
## Core Imports
12
13
```python
14
import stack_data
15
```
16
17
Common imports for core functionality:
18
19
```python
20
from stack_data import FrameInfo, Options, Formatter, Serializer
21
```
22
23
For specific classes and functions:
24
25
```python
26
from stack_data import (
27
Source, FrameInfo, Options, Variable, Line,
28
markers_from_ranges, style_with_executing_node,
29
Formatter, Serializer, BlankLines, RangeInLine,
30
MarkerInLine, LINE_GAP, RepeatedFrames, BlankLineRange
31
)
32
```
33
34
## Basic Usage
35
36
```python
37
import inspect
38
from stack_data import FrameInfo, Formatter
39
40
# Get current frame and create FrameInfo
41
frame = inspect.currentframe()
42
frame_info = FrameInfo(frame)
43
44
# Display lines with context
45
for line in frame_info.lines:
46
if hasattr(line, 'text'):
47
print(f"{line.lineno}: {line.text}")
48
49
# Use Formatter for enhanced display
50
formatter = Formatter(show_variables=True, pygmented=True)
51
formatter.print_stack()
52
53
# Exception handling with enhanced display
54
try:
55
# Some code that might raise an exception
56
result = 1 / 0
57
except Exception as e:
58
formatter.print_exception(e)
59
```
60
61
## Architecture
62
63
Stack Data provides a layered architecture for stack frame analysis:
64
65
- **FrameInfo**: Central class that extracts rich information from stack frames, including source code context, variable values, and execution state
66
- **Source**: Enhanced source code representation with AST parsing, tokenization, and metadata
67
- **Options**: Configuration system for controlling display behavior, context size, and formatting preferences
68
- **Variable**: Expression evaluation system using pure_eval for safe variable inspection
69
- **Formatters**: Multiple output formats (text display, HTML, structured data) for different use cases
70
71
This design enables flexible stack trace analysis and display, supporting everything from simple debugging output to sophisticated educational tools and development environments.
72
73
## Capabilities
74
75
### Stack Frame Analysis
76
77
Core functionality for analyzing Python stack frames and extracting detailed information including source code context, variable values, and execution state.
78
79
```python { .api }
80
class FrameInfo:
81
def __init__(self, frame_or_tb, options=None): ...
82
@classmethod
83
def stack_data(cls, frame_or_tb, options=None, *, collapse_repeated_frames=True): ...
84
85
class Options:
86
def __init__(self, *, before=3, after=1, include_signature=False,
87
max_lines_per_piece=6, pygments_formatter=None,
88
blank_lines=BlankLines.HIDDEN): ...
89
90
class Source:
91
@property
92
def pieces(self): ...
93
@property
94
def tokens_by_lineno(self): ...
95
```
96
97
[Stack Frame Analysis](./frame-analysis.md)
98
99
### Text Formatting
100
101
Comprehensive text formatting system for displaying stack traces and frame information with syntax highlighting, variable display, and customizable output options.
102
103
```python { .api }
104
class Formatter:
105
def __init__(self, *, options=None, pygmented=False, show_executing_node=True,
106
show_variables=False, show_linenos=True, html=False,
107
chain=True, collapse_repeated_frames=True): ...
108
109
def print_exception(self, e=None, *, file=None): ...
110
def print_stack(self, frame_or_tb=None, *, file=None): ...
111
def format_exception(self, e=None): ...
112
def format_stack(self, frame_or_tb=None): ...
113
```
114
115
[Text Formatting](./formatting.md)
116
117
### Data Serialization
118
119
Structured data export functionality for converting stack traces and frame information into dictionaries and lists suitable for JSON serialization and programmatic processing.
120
121
```python { .api }
122
class Serializer:
123
def __init__(self, *, options=None, pygmented=False, show_executing_node=True,
124
use_code_qualname=True, strip_leading_indent=True, html=False,
125
chain=True, collapse_repeated_frames=True, show_variables=False): ...
126
127
def format_exception(self, e=None): ...
128
def format_stack(self, frame_or_tb=None): ...
129
def format_frame(self, frame): ...
130
```
131
132
[Data Serialization](./serialization.md)
133
134
## Types
135
136
```python { .api }
137
from typing import NamedTuple, Any, Sequence, List, Union, Optional, Mapping
138
from types import FrameType, TracebackType
139
from asttokens.util import Token
140
import ast
141
from enum import Enum
142
143
class Variable(NamedTuple):
144
name: str
145
nodes: Sequence[ast.AST]
146
value: Any
147
148
class RangeInLine(NamedTuple):
149
start: int
150
end: int
151
data: Any
152
153
class MarkerInLine(NamedTuple):
154
position: int
155
is_start: bool
156
string: str
157
158
class BlankLines(Enum):
159
HIDDEN = 1
160
VISIBLE = 2
161
SINGLE = 3
162
163
class LineGap:
164
"""
165
A singleton representing one or more lines of source code that were skipped.
166
"""
167
def __repr__(self) -> str: ...
168
169
class BlankLineRange:
170
def __init__(self, begin_lineno: int, end_lineno: int): ...
171
begin_lineno: int
172
end_lineno: int
173
174
class Line:
175
def __init__(self, frame_info: 'FrameInfo', lineno: int): ...
176
lineno: int
177
text: str
178
leading_indent: Optional[int]
179
is_current: bool
180
tokens: List[Token]
181
182
def render(self, markers=(), *, strip_leading_indent=True,
183
pygmented=False, escape_html=False) -> str: ...
184
def token_ranges(self) -> List[RangeInLine]: ...
185
def variable_ranges(self) -> List[RangeInLine]: ...
186
def executing_node_ranges(self) -> List[RangeInLine]: ...
187
def range_from_node(self, node: ast.AST, data: Any, common_indent: int = 0) -> Optional[RangeInLine]: ...
188
189
class RepeatedFrames:
190
def __init__(self, frames: List[Union[FrameType, TracebackType]],
191
frame_keys: List): ...
192
frames: List[Union[FrameType, TracebackType]]
193
description: str
194
```
195
196
### Constants
197
198
```python { .api }
199
LINE_GAP: LineGap # Singleton instance representing skipped lines
200
```