or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

ansi-styling.mddebug.mdindex.mdpretty-printing.mdpytest-plugin.mdtiming.md
tile.json

tessl/pypi-devtools

Python's missing debug print command and development tools with enhanced debugging, pretty printing, timing, and ANSI styling capabilities.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/devtools@0.12.x

To install, run

npx @tessl/cli install tessl/pypi-devtools@0.12.0

index.mddocs/

Devtools

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.

Package Information

  • Package Name: devtools
  • Language: Python
  • Installation: pip install devtools
  • Minimum Python Version: 3.7+

Core Imports

import devtools

Common imports for specific functionality:

from devtools import debug, Debug
from devtools import pprint, pformat, PrettyFormat
from devtools import Timer
from devtools import sformat, sprint
from devtools import VERSION

Basic Usage

from devtools import debug

# Debug variables with automatic name extraction and context
data = {'users': [1, 2, 3], 'active': True}
debug(data)
# Output: example.py:4 <module>:
#     data: {
#         'users': [1, 2, 3],
#         'active': True,
#     } (dict) len=2

# Pretty print complex data structures
from devtools import pprint
import numpy as np

complex_data = {
    'matrix': np.array([[1, 2], [3, 4]]),
    'nested': {'a': [1, 2, 3], 'b': set([4, 5, 6])},
    'text': 'This is a long string that might wrap'
}
pprint(complex_data)

# Time code execution
from devtools import Timer

with Timer('database query'):
    # Some operation
    import time
    time.sleep(0.1)
# Output: database query: 0.101s elapsed

Architecture

Devtools is built around four core modules that work together to provide comprehensive development utilities:

  • 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
  • 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
  • Timer Utilities: High-precision performance measurement using perf_counter() with context manager support and statistical analysis of multiple timing runs
  • ANSI Styling: Cross-platform ANSI escape sequence handling with Windows console activation and automatic TTY detection for colored terminal output

Capabilities

Debug Printing

Enhanced debug printing that automatically extracts variable names, displays types and metadata, shows source location, and provides syntax highlighting with intelligent pretty formatting.

def debug(*args, file_=None, flush_=True, frame_depth_=2, **kwargs):
    """
    Debug print with automatic variable name extraction and context.
    
    Parameters:
    - *args: Variables to debug print
    - file_: Output file (default: stdout)
    - flush_: Flush output buffer (default: True)
    - frame_depth_: Stack frame depth for inspection (default: 2)
    - **kwargs: Named variables to debug print
    
    Returns:
    Single arg: the arg itself
    Multiple args: tuple of args
    With kwargs: (*args, kwargs)
    """

class Debug:
    """
    Configurable debug print class.
    """
    def __init__(self, warnings=None, highlight=None): ...
    def __call__(self, *args, **kwargs): ...
    def format(self, *args, **kwargs) -> DebugOutput: ...
    def breakpoint(self) -> None: ...
    def timer(self, name=None, verbose=True, file=None, dp=3) -> Timer: ...

Debug System

Pretty Printing

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.

def pformat(value, indent=0, indent_first=False, highlight=False) -> str:
    """
    Format value as pretty string.
    
    Parameters:
    - value: Object to format
    - indent: Initial indentation level
    - indent_first: Indent the first line
    - highlight: Apply syntax highlighting
    
    Returns:
    Formatted string representation
    """

def pprint(s, file=None) -> None:
    """
    Pretty print with automatic highlighting detection.
    
    Parameters:
    - s: Object to pretty print
    - file: Output file (default: stdout)
    """

class PrettyFormat:
    """
    Configurable pretty formatter.
    """
    def __init__(
        self,
        indent_step=4,
        indent_char=' ',
        repr_strings=False,
        simple_cutoff=10,
        width=120,
        yield_from_generators=True
    ): ...

Pretty Printing

Timing and Performance

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.

class Timer:
    """
    High-precision timer for performance measurement.
    """
    def __init__(self, name=None, verbose=True, file=None, dp=3): ...
    def __call__(self, name=None, verbose=None) -> Timer: ...
    def start(self, name=None, verbose=None) -> Timer: ...
    def capture(self, verbose=None) -> TimerResult: ...
    def summary(self, verbose=False) -> list[float]: ...
    def __enter__(self) -> Timer: ...
    def __exit__(self, *args) -> None: ...

class TimerResult:
    """
    Represents a single timing measurement.
    """
    def __init__(self, name=None, verbose=True): ...
    def capture(self) -> None: ...
    def elapsed(self) -> float: ...
    def str(self, dp=3) -> str: ...

Timing

ANSI Styling

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.

def sformat(input, *styles, reset=True, apply=True) -> str:
    """
    Format text with ANSI styles.
    
    Parameters:
    - input: Text to style
    - *styles: Style codes to apply
    - reset: Append reset code (default: True)
    - apply: Apply styling (default: True)
    
    Returns:
    Styled text string
    """

def sprint(input, *styles, reset=True, flush=True, file=None, **print_kwargs) -> None:
    """
    Print text with ANSI styling.
    
    Parameters:
    - input: Text to print
    - *styles: Style codes to apply
    - reset: Append reset code (default: True)
    - flush: Flush output (default: True)
    - file: Output file (default: stdout)
    - **print_kwargs: Additional print arguments
    """

class Style(IntEnum):
    """ANSI style codes enum with styling function."""
    # Text styles
    reset = 0
    bold = 1
    dim = 2
    italic = 3
    underline = 4
    blink = 5
    reverse = 7
    strike_through = 9
    
    # Foreground colors
    black = 30
    red = 31
    green = 32
    yellow = 33
    blue = 34
    magenta = 35
    cyan = 36
    white = 37
    
    # Background colors
    bg_black = 40
    bg_red = 41
    bg_green = 42
    bg_yellow = 43
    bg_blue = 44
    bg_magenta = 45
    bg_cyan = 46
    bg_white = 47

ANSI Styling

Pytest Integration

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.

def insert_assert(value) -> int:
    """
    Insert assert statement for testing (requires Python 3.8+).
    
    Parameters:
    - value: Value to create assert statement for
    
    Returns:
    Number of insert_assert calls in current test
    """

Pytest Plugin

Environment Variables

Devtools behavior can be customized through environment variables:

  • PY_DEVTOOLS_INDENT: Default indentation step (default: 4)
  • PY_DEVTOOLS_SIMPLE_CUTOFF: Simple representation cutoff (default: 10)
  • PY_DEVTOOLS_WIDTH: Output width for formatting (default: 120)
  • PY_DEVTOOLS_YIELD_FROM_GEN: Yield from generators in pretty print (default: True)
  • PY_DEVTOOLS_WARNINGS: Show debug warnings (default: True)
  • PY_DEVTOOLS_HIGHLIGHT: Force syntax highlighting on/off

Installation Without Import

For global access without imports, devtools can be installed into Python's builtins:

python -m devtools install

This provides instructions for adding debug functionality to sitecustomize.py, making debug() available in all Python sessions without explicit imports.

Types

class DebugOutput:
    """Represents formatted debug output."""
    def __init__(self, filename: str, lineno: int, frame: str, arguments: list[DebugArgument], warning: str | bool | None = None): ...
    def str(self, highlight: bool = False) -> str: ...

class DebugArgument:
    """Represents a single debug argument with name and value."""
    def __init__(self, value, name: str | None = None, **extra): ...
    def str(self, highlight: bool = False) -> str: ...

VERSION: str  # Package version string