0
# Traceback with Variables
1
2
A Python debugging library that enhances exception tracebacks by automatically including local variable values and contexts for each frame in the stack trace. Provides multiple output formats including colorful console printing, file logging, and integration with standard Python logging systems, with built-in support for Jupyter notebooks and IPython environments.
3
4
## Package Information
5
6
- **Package Name**: traceback-with-variables
7
- **Language**: Python
8
- **Installation**: `pip install traceback-with-variables`
9
- **Python Version**: >=3.6
10
- **Dependencies**: None (zero dependencies)
11
12
## Core Imports
13
14
```python
15
import traceback_with_variables
16
```
17
18
Common imports for direct usage:
19
20
```python
21
from traceback_with_variables import print_exc, Format, printing_exc
22
from traceback_with_variables import default_format as fmt
23
```
24
25
The `fmt` alias provides convenient access to the global default format configuration:
26
27
```python
28
from traceback_with_variables import fmt # Short alias for default_format
29
30
# Modify global formatting for all subsequent traceback calls
31
fmt.max_value_str_len = 500
32
fmt.before = 1
33
fmt.after = 1
34
```
35
36
Auto-activation imports:
37
38
```python
39
# Auto-activate in any environment
40
import traceback_with_variables.activate_by_import
41
42
# Auto-activate in Python (not Jupyter/IPython)
43
import traceback_with_variables.activate_in_python_by_import
44
45
# Auto-activate in Jupyter/IPython only
46
import traceback_with_variables.activate_in_ipython_by_import
47
```
48
49
## Basic Usage
50
51
### Manual Exception Printing
52
53
```python
54
from traceback_with_variables import print_exc
55
56
try:
57
x = 42
58
y = "hello"
59
result = x / 0 # This will raise ZeroDivisionError
60
except Exception as e:
61
print_exc(e) # Print enhanced traceback with variables
62
```
63
64
### Context Manager
65
66
```python
67
from traceback_with_variables import printing_exc
68
69
x = 42
70
y = "hello"
71
72
with printing_exc():
73
result = x / 0 # Enhanced traceback printed automatically
74
```
75
76
### Global Hook Installation
77
78
```python
79
from traceback_with_variables import global_print_exc
80
81
# Install global hook for all exceptions
82
global_print_exc()
83
84
# Now all unhandled exceptions show variables
85
x = 42
86
y = "hello"
87
result = x / 0 # Enhanced traceback displayed automatically
88
```
89
90
### Simplest Usage (Auto-activation)
91
92
```python
93
# Just import to auto-activate in any environment
94
import traceback_with_variables.activate_by_import
95
96
# All exceptions now show variables automatically
97
x = 42
98
y = "hello"
99
result = x / 0 # Enhanced traceback displayed
100
```
101
102
## Architecture
103
104
The library uses a modular architecture centered around formatting configuration:
105
106
- **Format**: Central configuration class controlling all aspects of traceback formatting
107
- **Core Functions**: Low-level traceback processing and formatting engine
108
- **Print Functions**: High-level interfaces for different output scenarios
109
- **Global Hooks**: Integration with Python's exception handling system
110
- **Color System**: ANSI terminal color support with auto-detection
111
- **Auto-activation**: Zero-configuration import-based activation
112
113
## Capabilities
114
115
### Core Formatting and Display
116
117
Central formatting engine that processes tracebacks and displays variable contexts. Provides low-level functions for creating formatted traceback strings and iterating through traceback lines.
118
119
```python { .api }
120
def format_exc(e=None, num_skipped_frames=0, fmt=None, for_file=None): ...
121
def format_cur_tb(num_skipped_frames=0, fmt=None, for_file=None): ...
122
def iter_exc_lines(e=None, num_skipped_frames=0, fmt=None, for_file=None): ...
123
def iter_cur_tb_lines(num_skipped_frames=0, fmt=None, for_file=None): ...
124
def skip(obj): ...
125
def hide(obj): ...
126
def show(obj): ...
127
default_format: Format
128
```
129
130
[Core Formatting](./core-formatting.md)
131
132
### Printing and Context Management
133
134
High-level printing functions and context managers for displaying enhanced tracebacks to various output destinations including files, loggers, and standard streams.
135
136
```python { .api }
137
def print_exc(e=None, num_skipped_frames=0, fmt=None, file_=sys.stderr): ...
138
def print_cur_tb(num_skipped_frames=0, fmt=None, file_=sys.stderr): ...
139
def printing_exc(reraise=True, file_=sys.stderr, skip_cur_frame=False, fmt=None): ...
140
def prints_exc(func=None, file_=sys.stderr, fmt=None): ...
141
```
142
143
[Printing and Context Management](./printing.md)
144
145
### Configuration and Formatting
146
147
Comprehensive formatting configuration system with customizable output options, color schemes, variable filtering, and display preferences.
148
149
```python { .api }
150
class Format:
151
def __init__(
152
self,
153
max_value_str_len=1000,
154
ellipsis_rel_pos=0.7,
155
max_exc_str_len=10000,
156
objects_details=1,
157
ellipsis_='...',
158
before=0,
159
after=0,
160
color_scheme=None,
161
skip_files_except=None,
162
brief_files_except=None,
163
custom_var_printers=None
164
): ...
165
```
166
167
[Configuration and Formatting](./configuration.md)
168
169
### Global Exception Hooks
170
171
System-level integration that replaces Python's default exception handling with enhanced traceback display, supporting both standard Python and IPython/Jupyter environments.
172
173
```python { .api }
174
def global_print_exc(fmt=None): ...
175
def global_print_exc_in_ipython(fmt=None): ...
176
def in_ipython() -> bool: ...
177
def is_ipython_global(name: str, type_: Type, filename: str, is_global: bool) -> bool: ...
178
```
179
180
[Global Exception Hooks](./global-hooks.md)
181
182
### Color and Terminal Support
183
184
ANSI color system with automatic terminal capability detection and pre-defined color schemes for different environments and preferences.
185
186
```python { .api }
187
class ColorScheme: ...
188
class ColorSchemes: ...
189
def supports_ansi(file_): ...
190
```
191
192
[Color and Terminal Support](./color-system.md)
193
194
### Default Global Hooks and Auto-activation
195
196
Pre-configured global exception hooks and auto-activation modules that provide zero-configuration enhanced tracebacks with sensible defaults including environment-appropriate variable filtering.
197
198
```python { .api }
199
def default_global_print_exc() -> None: ...
200
def default_global_print_exc_in_ipython() -> None: ...
201
def default_global_print_exc_in_all() -> None: ...
202
```
203
204
[Default Global Hooks and Auto-activation](./default-hooks.md)
205
206
### Command Line Interface
207
208
Command-line tool for running Python scripts with enhanced traceback display, supporting all formatting options and providing a complete wrapper for script execution with variable contexts.
209
210
```python { .api }
211
def run_script(path: Path, argv: List[str], fmt: Format) -> int: ...
212
def main() -> int: ...
213
def parse_args() -> Tuple[argparse.Namespace, Path, List[str]]: ...
214
class ParseError(RuntimeError): ...
215
```
216
217
[Command Line Interface](./cli-interface.md)
218
219
### Utilities and Aliases
220
221
Utility functions and module aliasing system for enhanced convenience, including filesystem-based module aliases for shorter imports and ANSI color code utilities.
222
223
```python { .api }
224
def create_alias(alias: str, module_name: str) -> None: ...
225
def rm_alias(alias: str) -> None: ...
226
def create_tb_alias() -> None: ...
227
def rm_tb_alias() -> None: ...
228
def to_ansi(str_: str) -> str: ...
229
```
230
231
[Utilities and Aliases](./utilities.md)
232
233
## Types
234
235
```python { .api }
236
# Type aliases for configuration
237
Patterns = Union[None, str, List[str]] # File filter patterns
238
ShouldPrint = Callable[[str, Type, str, bool], bool] # Variable filter function
239
VarFilterItem = Union[str, Type, ShouldPrint] # Single variable filter
240
VarFilter = Union[VarFilterItem, List[VarFilterItem]] # Complete variable filter
241
Print = Callable[[Any], Optional[str]] # Custom variable printer function
242
VarPrinters = List[Tuple[ShouldPrint, Print]] # Filter-printer pairs
243
244
# Main configuration class
245
class Format:
246
max_value_str_len: int
247
ellipsis_rel_pos: float
248
max_exc_str_len: int
249
objects_details: int
250
ellipsis_: str
251
before: int
252
after: int
253
color_scheme: Optional[ColorScheme]
254
skip_files_except: List[re.Pattern]
255
brief_files_except: List[re.Pattern]
256
custom_var_printers: VarPrinters
257
258
@classmethod
259
def add_arguments(cls, parser: argparse.ArgumentParser) -> None: ...
260
261
@classmethod
262
def parse(cls, ns: argparse.Namespace) -> 'Format': ...
263
264
def replace(self, **kwargs) -> 'Format': ...
265
266
# Color system classes
267
class ColorScheme:
268
def __init__(
269
self,
270
common: str,
271
file_: str,
272
line_num: str,
273
func_name: str,
274
func_snippet: str,
275
name: str,
276
value: str,
277
exc_class: str,
278
exc_text: str,
279
end: str
280
): ...
281
282
class ColorSchemes:
283
auto: None
284
none: ColorScheme
285
common: ColorScheme
286
synthwave: ColorScheme
287
nice: ColorScheme
288
289
# Logger adapter for file-like interface
290
class LoggerAsFile:
291
def __init__(self, logger: logging.Logger, separate_lines: bool = False): ...
292
def write(self, text: str) -> None: ...
293
def flush(self) -> None: ...
294
```