0
# Printing and Context Management
1
2
High-level printing functions and context managers for displaying enhanced tracebacks to various output destinations including files, loggers, and standard streams. Provides convenient interfaces for exception handling with automatic variable display.
3
4
## Capabilities
5
6
### Exception Printing
7
8
Print exception tracebacks with variable contexts to files or file-like objects.
9
10
```python { .api }
11
def print_exc(
12
e: Optional[Exception] = None,
13
num_skipped_frames: int = 0,
14
fmt: Optional[Format] = None,
15
file_: Union[TextIO, LoggerAsFile] = sys.stderr,
16
) -> None:
17
"""
18
Print exception traceback with variable contexts.
19
20
Parameters:
21
- e: Exception to print (uses current exception if None)
22
- num_skipped_frames: Number of frames to skip from the top
23
- fmt: Format configuration (uses default_format if None)
24
- file_: Output destination (file object or LoggerAsFile)
25
"""
26
```
27
28
### Current Traceback Printing
29
30
Print the current call stack with variable contexts.
31
32
```python { .api }
33
def print_cur_tb(
34
num_skipped_frames: int = 0,
35
fmt: Optional[Format] = None,
36
file_: Union[TextIO, LoggerAsFile] = sys.stderr,
37
) -> None:
38
"""
39
Print current traceback with variable contexts.
40
41
Parameters:
42
- num_skipped_frames: Number of frames to skip from the top
43
- fmt: Format configuration (uses default_format if None)
44
- file_: Output destination (file object or LoggerAsFile)
45
"""
46
```
47
48
### Exception Context Manager
49
50
Context manager that automatically prints exceptions with variable contexts when they occur.
51
52
```python { .api }
53
def printing_exc(
54
reraise: bool = True,
55
file_: Union[TextIO, LoggerAsFile] = sys.stderr,
56
skip_cur_frame: bool = False,
57
fmt: Optional[Format] = None,
58
):
59
"""
60
Context manager that prints exceptions with variable contexts.
61
62
Parameters:
63
- reraise: Whether to re-raise the exception after printing
64
- file_: Output destination (file object or LoggerAsFile)
65
- skip_cur_frame: Skip the current frame from traceback
66
- fmt: Format configuration (uses default_format if None)
67
68
Usage:
69
with printing_exc():
70
# Code that might raise exceptions
71
pass
72
"""
73
```
74
75
### Exception Decorator
76
77
Decorator that prints exceptions with variable contexts when functions raise them.
78
79
```python { .api }
80
def prints_exc(
81
func__for_noncall_case_only: Optional[Callable] = None,
82
file_: Union[TextIO, LoggerAsFile] = sys.stderr,
83
fmt: Optional[Format] = None,
84
):
85
"""
86
Decorator that prints exceptions with variable contexts.
87
88
Parameters:
89
- func__for_noncall_case_only: Function to decorate (for @prints_exc syntax)
90
- file_: Output destination (file object or LoggerAsFile)
91
- fmt: Format configuration (uses default_format if None)
92
93
Usage:
94
@prints_exc
95
def my_function():
96
pass
97
98
# Or with parameters:
99
@prints_exc(file_=my_file, fmt=my_format)
100
def my_function():
101
pass
102
"""
103
```
104
105
### Logger Integration
106
107
Adapter class that allows Python loggers to be used as file-like objects for traceback output.
108
109
```python { .api }
110
class LoggerAsFile:
111
def __init__(self, logger: logging.Logger, separate_lines: bool = False):
112
"""
113
Create a file-like adapter for a Python logger.
114
115
Parameters:
116
- logger: Python logger instance to write to
117
- separate_lines: If True, log each line separately; if False, collect lines and log together
118
"""
119
120
def write(self, text: str) -> None:
121
"""
122
Write text to the logger.
123
124
Parameters:
125
- text: Text to write/log
126
"""
127
128
def flush(self) -> None:
129
"""Flush any buffered content to the logger."""
130
```
131
132
## Usage Examples
133
134
### Basic Exception Printing
135
136
```python
137
from traceback_with_variables import print_exc
138
139
try:
140
x = 42
141
y = "hello"
142
result = x / 0
143
except Exception as e:
144
print_exc(e) # Print to stderr with variables
145
```
146
147
### Custom Output Destination
148
149
```python
150
from traceback_with_variables import print_exc
151
import sys
152
153
try:
154
data = [1, 2, 3]
155
index = 5
156
value = data[index]
157
except Exception as e:
158
# Print to stdout instead of stderr
159
print_exc(e, file_=sys.stdout)
160
161
# Print to a file
162
with open('error.log', 'w') as f:
163
print_exc(e, file_=f)
164
```
165
166
### Context Manager Usage
167
168
```python
169
from traceback_with_variables import printing_exc
170
171
# Automatically print exceptions but don't reraise
172
with printing_exc(reraise=False):
173
x = 42
174
y = 0
175
result = x / y # Exception printed, execution continues
176
177
print("This line executes because reraise=False")
178
179
# Print exceptions and reraise (default behavior)
180
try:
181
with printing_exc():
182
items = [1, 2, 3]
183
value = items[10] # Exception printed and reraised
184
except IndexError:
185
print("Caught the reraised exception")
186
```
187
188
### Decorator Usage
189
190
```python
191
from traceback_with_variables import prints_exc
192
193
# Simple decorator usage
194
@prints_exc
195
def risky_function():
196
x = 42
197
y = 0
198
return x / y
199
200
# Decorator with custom parameters
201
@prints_exc(file_=open('errors.log', 'a'))
202
def logged_function():
203
data = {"key": "value"}
204
return data["missing_key"]
205
206
# Call functions - exceptions will be printed automatically
207
try:
208
risky_function()
209
except ZeroDivisionError:
210
print("Function completed with exception handling")
211
```
212
213
### Logger Integration
214
215
```python
216
import logging
217
from traceback_with_variables import print_exc, LoggerAsFile
218
219
# Set up logger
220
logger = logging.getLogger('my_app')
221
logger.setLevel(logging.ERROR)
222
handler = logging.FileHandler('app_errors.log')
223
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
224
handler.setFormatter(formatter)
225
logger.addHandler(handler)
226
227
# Create logger adapter
228
logger_file = LoggerAsFile(logger, separate_lines=False)
229
230
try:
231
config = {"database": {"host": "localhost"}}
232
db_config = config["database"]["port"] # Missing key
233
except Exception as e:
234
# Print exception to logger instead of console
235
print_exc(e, file_=logger_file)
236
```
237
238
### Advanced Context Management
239
240
```python
241
from traceback_with_variables import printing_exc, Format, ColorSchemes
242
243
# Custom format for context manager
244
custom_fmt = Format(
245
max_value_str_len=200,
246
color_scheme=ColorSchemes.nice,
247
before=1,
248
after=1
249
)
250
251
# Use custom format with context manager
252
with printing_exc(fmt=custom_fmt, skip_cur_frame=True):
253
nested_data = {
254
"users": [
255
{"id": 1, "name": "Alice"},
256
{"id": 2, "name": "Bob"}
257
]
258
}
259
user_id = 3
260
user = next(u for u in nested_data["users"] if u["id"] == user_id)
261
```
262
263
### Multiple Output Destinations
264
265
```python
266
from traceback_with_variables import print_exc
267
import sys
268
269
try:
270
items = list(range(10))
271
calculation = items[5] / items[0] # This will work
272
problem = items[15] # This will fail
273
except Exception as e:
274
# Print to multiple destinations
275
print("ERROR OCCURRED:", file=sys.stderr)
276
print_exc(e, file_=sys.stderr)
277
278
# Also log to file
279
with open('detailed_errors.log', 'a') as log_file:
280
print_exc(e, file_=log_file)
281
```