Python's missing debug print command and development tools with enhanced debugging, pretty printing, timing, and ANSI styling capabilities.
npx @tessl/cli install tessl/pypi-devtools@0.12.00
# Devtools
1
2
Python's missing debug print command and comprehensive development toolkit. Devtools provides enhanced debugging capabilities with variable name extraction, pretty printing for complex data structures, high-precision timing utilities, and ANSI color formatting - all designed to improve Python developer productivity during debugging, development, and testing.
3
4
## Package Information
5
6
- **Package Name**: devtools
7
- **Language**: Python
8
- **Installation**: `pip install devtools`
9
- **Minimum Python Version**: 3.7+
10
11
## Core Imports
12
13
```python
14
import devtools
15
```
16
17
Common imports for specific functionality:
18
19
```python
20
from devtools import debug, Debug
21
from devtools import pprint, pformat, PrettyFormat
22
from devtools import Timer
23
from devtools import sformat, sprint
24
from devtools import VERSION
25
```
26
27
## Basic Usage
28
29
```python
30
from devtools import debug
31
32
# Debug variables with automatic name extraction and context
33
data = {'users': [1, 2, 3], 'active': True}
34
debug(data)
35
# Output: example.py:4 <module>:
36
# data: {
37
# 'users': [1, 2, 3],
38
# 'active': True,
39
# } (dict) len=2
40
41
# Pretty print complex data structures
42
from devtools import pprint
43
import numpy as np
44
45
complex_data = {
46
'matrix': np.array([[1, 2], [3, 4]]),
47
'nested': {'a': [1, 2, 3], 'b': set([4, 5, 6])},
48
'text': 'This is a long string that might wrap'
49
}
50
pprint(complex_data)
51
52
# Time code execution
53
from devtools import Timer
54
55
with Timer('database query'):
56
# Some operation
57
import time
58
time.sleep(0.1)
59
# Output: database query: 0.101s elapsed
60
```
61
62
## Architecture
63
64
Devtools is built around four core modules that work together to provide comprehensive development utilities:
65
66
- **Debug System**: Leverages `executing` and `asttokens` libraries to extract variable names and source context from the call stack, enabling intelligent debug output without manual naming
67
- **Pretty Printer**: Recursive formatter that handles complex Python objects including dataclasses, SQLAlchemy models, numpy arrays, and nested structures with intelligent line wrapping and syntax highlighting
68
- **Timer Utilities**: High-precision performance measurement using `perf_counter()` with context manager support and statistical analysis of multiple timing runs
69
- **ANSI Styling**: Cross-platform ANSI escape sequence handling with Windows console activation and automatic TTY detection for colored terminal output
70
71
## Capabilities
72
73
### Debug Printing
74
75
Enhanced debug printing that automatically extracts variable names, displays types and metadata, shows source location, and provides syntax highlighting with intelligent pretty formatting.
76
77
```python { .api }
78
def debug(*args, file_=None, flush_=True, frame_depth_=2, **kwargs):
79
"""
80
Debug print with automatic variable name extraction and context.
81
82
Parameters:
83
- *args: Variables to debug print
84
- file_: Output file (default: stdout)
85
- flush_: Flush output buffer (default: True)
86
- frame_depth_: Stack frame depth for inspection (default: 2)
87
- **kwargs: Named variables to debug print
88
89
Returns:
90
Single arg: the arg itself
91
Multiple args: tuple of args
92
With kwargs: (*args, kwargs)
93
"""
94
95
class Debug:
96
"""
97
Configurable debug print class.
98
"""
99
def __init__(self, warnings=None, highlight=None): ...
100
def __call__(self, *args, **kwargs): ...
101
def format(self, *args, **kwargs) -> DebugOutput: ...
102
def breakpoint(self) -> None: ...
103
def timer(self, name=None, verbose=True, file=None, dp=3) -> Timer: ...
104
```
105
106
[Debug System](./debug.md)
107
108
### Pretty Printing
109
110
Advanced pretty printing for complex Python data structures with intelligent formatting, syntax highlighting, configurable output width, and special handling for dataclasses, numpy arrays, and custom objects.
111
112
```python { .api }
113
def pformat(value, indent=0, indent_first=False, highlight=False) -> str:
114
"""
115
Format value as pretty string.
116
117
Parameters:
118
- value: Object to format
119
- indent: Initial indentation level
120
- indent_first: Indent the first line
121
- highlight: Apply syntax highlighting
122
123
Returns:
124
Formatted string representation
125
"""
126
127
def pprint(s, file=None) -> None:
128
"""
129
Pretty print with automatic highlighting detection.
130
131
Parameters:
132
- s: Object to pretty print
133
- file: Output file (default: stdout)
134
"""
135
136
class PrettyFormat:
137
"""
138
Configurable pretty formatter.
139
"""
140
def __init__(
141
self,
142
indent_step=4,
143
indent_char=' ',
144
repr_strings=False,
145
simple_cutoff=10,
146
width=120,
147
yield_from_generators=True
148
): ...
149
```
150
151
[Pretty Printing](./pretty-printing.md)
152
153
### Timing and Performance
154
155
High-precision timing utilities for performance measurement and profiling with context manager support, multiple timing runs, and statistical analysis including mean, standard deviation, min, and max calculations.
156
157
```python { .api }
158
class Timer:
159
"""
160
High-precision timer for performance measurement.
161
"""
162
def __init__(self, name=None, verbose=True, file=None, dp=3): ...
163
def __call__(self, name=None, verbose=None) -> Timer: ...
164
def start(self, name=None, verbose=None) -> Timer: ...
165
def capture(self, verbose=None) -> TimerResult: ...
166
def summary(self, verbose=False) -> list[float]: ...
167
def __enter__(self) -> Timer: ...
168
def __exit__(self, *args) -> None: ...
169
170
class TimerResult:
171
"""
172
Represents a single timing measurement.
173
"""
174
def __init__(self, name=None, verbose=True): ...
175
def capture(self) -> None: ...
176
def elapsed(self) -> float: ...
177
def str(self, dp=3) -> str: ...
178
```
179
180
[Timing](./timing.md)
181
182
### ANSI Styling
183
184
Cross-platform ANSI color and style formatting for terminal output with Windows console support, automatic TTY detection, and comprehensive style options including colors, text formatting, and background colors.
185
186
```python { .api }
187
def sformat(input, *styles, reset=True, apply=True) -> str:
188
"""
189
Format text with ANSI styles.
190
191
Parameters:
192
- input: Text to style
193
- *styles: Style codes to apply
194
- reset: Append reset code (default: True)
195
- apply: Apply styling (default: True)
196
197
Returns:
198
Styled text string
199
"""
200
201
def sprint(input, *styles, reset=True, flush=True, file=None, **print_kwargs) -> None:
202
"""
203
Print text with ANSI styling.
204
205
Parameters:
206
- input: Text to print
207
- *styles: Style codes to apply
208
- reset: Append reset code (default: True)
209
- flush: Flush output (default: True)
210
- file: Output file (default: stdout)
211
- **print_kwargs: Additional print arguments
212
"""
213
214
class Style(IntEnum):
215
"""ANSI style codes enum with styling function."""
216
# Text styles
217
reset = 0
218
bold = 1
219
dim = 2
220
italic = 3
221
underline = 4
222
blink = 5
223
reverse = 7
224
strike_through = 9
225
226
# Foreground colors
227
black = 30
228
red = 31
229
green = 32
230
yellow = 33
231
blue = 34
232
magenta = 35
233
cyan = 36
234
white = 37
235
236
# Background colors
237
bg_black = 40
238
bg_red = 41
239
bg_green = 42
240
bg_yellow = 43
241
bg_blue = 44
242
bg_magenta = 45
243
bg_cyan = 46
244
bg_white = 47
245
```
246
247
[ANSI Styling](./ansi-styling.md)
248
249
### Pytest Integration
250
251
Pytest plugin for enhanced testing workflows with automatic assert statement insertion, test failure reporting with insert_assert tracking, and development-time debugging utilities integrated into the pytest environment.
252
253
```python { .api }
254
def insert_assert(value) -> int:
255
"""
256
Insert assert statement for testing (requires Python 3.8+).
257
258
Parameters:
259
- value: Value to create assert statement for
260
261
Returns:
262
Number of insert_assert calls in current test
263
"""
264
```
265
266
[Pytest Plugin](./pytest-plugin.md)
267
268
## Environment Variables
269
270
Devtools behavior can be customized through environment variables:
271
272
- `PY_DEVTOOLS_INDENT`: Default indentation step (default: 4)
273
- `PY_DEVTOOLS_SIMPLE_CUTOFF`: Simple representation cutoff (default: 10)
274
- `PY_DEVTOOLS_WIDTH`: Output width for formatting (default: 120)
275
- `PY_DEVTOOLS_YIELD_FROM_GEN`: Yield from generators in pretty print (default: True)
276
- `PY_DEVTOOLS_WARNINGS`: Show debug warnings (default: True)
277
- `PY_DEVTOOLS_HIGHLIGHT`: Force syntax highlighting on/off
278
279
## Installation Without Import
280
281
For global access without imports, devtools can be installed into Python's builtins:
282
283
```bash
284
python -m devtools install
285
```
286
287
This provides instructions for adding debug functionality to `sitecustomize.py`, making `debug()` available in all Python sessions without explicit imports.
288
289
## Types
290
291
```python { .api }
292
class DebugOutput:
293
"""Represents formatted debug output."""
294
def __init__(self, filename: str, lineno: int, frame: str, arguments: list[DebugArgument], warning: str | bool | None = None): ...
295
def str(self, highlight: bool = False) -> str: ...
296
297
class DebugArgument:
298
"""Represents a single debug argument with name and value."""
299
def __init__(self, value, name: str | None = None, **extra): ...
300
def str(self, highlight: bool = False) -> str: ...
301
302
VERSION: str # Package version string
303
```