Stack Data
stack-data is a Python library designed to extract detailed information from stack frames and tracebacks, offering more useful and customizable displays than Python's default tracebacks. It's currently at version 0.6.3 and is actively maintained, powering features in tools like IPython and futurecoder.
Warnings
- gotcha When inspecting recursive functions or deeply nested calls, `stack_data`, similar to Python's built-in traceback, automatically avoids showing all identical repeated frames. It instead provides a `RepeatedFrames` object. If you need to see every single frame, you must explicitly pass `collapse_repeated_frames=False` to `FrameInfo` (not to `Options`).
- gotcha When rendering lines that include markers (e.g., for highlighting or inserting HTML), ensure you use `line.render(markers, escape_html=True)` if you are inserting HTML. This will correctly escape special HTML characters in the Python source code to prevent malformed output, while still allowing your markers to be interpreted as HTML.
- gotcha The basic `line.render()` method strips common leading indentation. If preserving exact original indentation (including common leading whitespace) is critical for your display logic, be aware that `line.render()` modifies it. More advanced control over rendering and ranges is available via `line.token_ranges` or `line.range_from_node`.
Install
-
pip install stack-data
Imports
- FrameInfo
from stack_data import FrameInfo
- Options
from stack_data import Options
- Line
from stack_data import Line
Quickstart
import inspect
import stack_data
def foo():
result = []
for i in range(2):
row = []
result.append(row)
print_stack()
for j in range(2):
row.append(i * j)
return result
def print_stack():
frame = inspect.currentframe().f_back
frame_info = stack_data.FrameInfo(frame)
print(f"{frame_info.code.co_name} at line {frame_info.lineno}")
print("-----------")
for line in frame_info.lines:
print(f"{'-->' if line.is_current else ' '} {line.lineno:4} | {line.render()}")
foo()