CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-devtools

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

Pending
Overview
Eval results
Files

pretty-printing.mddocs/

Pretty Printing

Advanced pretty printing system for complex Python data structures with intelligent formatting, syntax highlighting, configurable output parameters, and special handling for various object types including dataclasses, numpy arrays, SQLAlchemy models, and custom objects with __pretty__ methods.

Capabilities

Pretty Format Function

The main pretty formatting function that converts Python objects to nicely formatted strings.

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

Usage examples:

from devtools import pformat

# Format complex nested data
data = {
    'users': [
        {'name': 'Alice', 'age': 30, 'active': True},
        {'name': 'Bob', 'age': 25, 'active': False}
    ],
    'config': {
        'debug': True,
        'timeout': 30.0,
        'retries': 3
    }
}

formatted = pformat(data, highlight=True)
print(formatted)
# Output: Nicely indented structure with syntax highlighting

# Format with custom indentation
formatted_indented = pformat(data, indent=4, indent_first=True)
print(formatted_indented)

Pretty Print Function

Convenience function that pretty prints directly to stdout or a file with automatic highlighting detection.

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

Usage examples:

from devtools import pprint
import numpy as np

# Pretty print to stdout with auto-highlighting
complex_data = {
    'matrix': np.array([[1, 2, 3], [4, 5, 6]]),
    'text': 'A very long string that will be wrapped appropriately for better readability',
    'nested': {'a': [1, 2, 3], 'b': {4, 5, 6}}
}
pprint(complex_data)

# Pretty print to file
with open('output.txt', 'w') as f:
    pprint(complex_data, file=f)

PrettyFormat Class

Configurable pretty formatting class that allows customization of all formatting parameters.

class PrettyFormat:
    """
    Configurable pretty formatter for complex data structures.
    """
    def __init__(
        self,
        indent_step: int = 4,
        indent_char: str = ' ',
        repr_strings: bool = False,
        simple_cutoff: int = 10,
        width: int = 120,
        yield_from_generators: bool = True
    ):
        """
        Initialize PrettyFormat with custom formatting options.
        
        Parameters:
        - indent_step: Number of spaces per indentation level (default: 4)
        - indent_char: Character used for indentation (default: ' ')
        - repr_strings: Use repr() for strings instead of pretty formatting (default: False)
        - simple_cutoff: Maximum length for simple one-line representation (default: 10)
        - width: Maximum line width for formatting (default: 120)
        - yield_from_generators: Iterate through generators for display (default: True)
        """
    
    def __call__(self, 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
        """

Usage examples:

from devtools import PrettyFormat

# Create custom formatter with different settings
compact_formatter = PrettyFormat(
    indent_step=2,
    width=80,
    simple_cutoff=20
)

# Create formatter that always uses repr for strings
repr_formatter = PrettyFormat(repr_strings=True)

# Use custom formatter
data = {'key': 'value', 'numbers': [1, 2, 3, 4, 5]}
compact_output = compact_formatter(data)
repr_output = repr_formatter(data)

Special Object Support

The pretty printer includes built-in support for various special object types:

Dataclasses

from dataclasses import dataclass
from devtools import pprint

@dataclass
class Person:
    name: str
    age: int
    active: bool = True

person = Person("Alice", 30)
pprint(person)
# Output: Person(
#     name='Alice',
#     age=30,
#     active=True,
# )

Named Tuples

from collections import namedtuple
from devtools import pprint

Point = namedtuple('Point', ['x', 'y', 'z'])
point = Point(1.0, 2.0, 3.0)
pprint(point)
# Output: Point(
#     x=1.0,
#     y=2.0,
#     z=3.0,
# )

Generators and Iterators

from devtools import pprint

def number_generator():
    for i in range(5):
        yield i * 2

# Generator contents are displayed when yield_from_generators=True
pprint(number_generator())
# Output: (
#     0,
#     2,
#     4,
#     6,
#     8,
# )

Long Strings and Multiline Text

from devtools import pprint

long_text = "This is a very long string that will be wrapped across multiple lines to improve readability and fit within the specified width constraints."

pprint(long_text)
# Output: (
#     'This is a very long string that will be wrapped across '
#     'multiple lines to improve readability and fit within the '
#     'specified width constraints.'
# )

Custom Pretty Methods

Objects can implement custom pretty formatting by defining a __pretty__ method:

class CustomObject:
    def __init__(self, data):
        self.data = data
    
    def __pretty__(self, fmt, skip_exc):
        yield 'CustomObject('
        yield 1  # Increase indentation
        yield fmt({'data': self.data})
        yield -1  # Decrease indentation
        yield ')'

from devtools import pprint
obj = CustomObject([1, 2, 3])
pprint(obj)
# Output: CustomObject(
#     {'data': [1, 2, 3]}
# )

Format Helper Function

Utility function for custom pretty formatting implementations.

def fmt(v) -> dict:
    """
    Helper function for custom pretty formatting.
    
    Parameters:
    - v: Value to format
    
    Returns:
    Dictionary with special pretty formatting key
    """

Skip Pretty Exception

Exception class for skipping pretty formatting in custom __pretty__ methods.

class SkipPretty(Exception):
    """
    Exception raised to skip pretty formatting and fall back to repr().
    """

Usage in custom __pretty__ methods:

class ConditionalPretty:
    def __init__(self, data, should_pretty=True):
        self.data = data
        self.should_pretty = should_pretty
    
    def __pretty__(self, fmt, skip_exc):
        if not self.should_pretty:
            raise skip_exc  # Falls back to repr()
        yield f'ConditionalPretty({self.data})'

SQLAlchemy Integration

Special support for SQLAlchemy ORM models with deferred attribute handling:

# Assuming SQLAlchemy model
from devtools import pprint

# SQLAlchemy model instance
user = User(name="Alice", email="alice@example.com")
pprint(user)
# Output: User(
#     id=1,
#     name='Alice',
#     email='alice@example.com',
#     posts=<deferred>,  # Deferred attributes shown as <deferred>
# )

Environment Variables

Pretty printing behavior can be customized via environment variables:

  • PY_DEVTOOLS_INDENT: Default indentation step (default: 4)
  • PY_DEVTOOLS_SIMPLE_CUTOFF: Simple representation cutoff (default: 10)
  • PY_DEVTOOLS_WIDTH: Output width (default: 120)
  • PY_DEVTOOLS_YIELD_FROM_GEN: Yield from generators (default: True)
  • PY_DEVTOOLS_HIGHLIGHT: Force highlighting on/off

Types

# Default pretty formatter instance
pformat: PrettyFormat

# Internal constants
MISSING: object  # Sentinel object for missing values
PRETTY_KEY: str  # Key for pretty formatting dict

Install with Tessl CLI

npx tessl i tessl/pypi-devtools

docs

ansi-styling.md

debug.md

index.md

pretty-printing.md

pytest-plugin.md

timing.md

tile.json