CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-prettyprinter

Syntax-highlighting, declarative and composable pretty printer for Python 3.5+

Pending
Overview
Eval results
Files

core-printing.mddocs/

Core Pretty Printing

Primary functions for pretty printing Python objects with comprehensive formatting options. These functions provide both plain text and syntax-highlighted output with extensive customization capabilities.

Capabilities

Plain Text Pretty Printing

Pretty print Python objects to a stream or string without syntax highlighting, providing optimal layout within specified width constraints.

def pprint(object, stream=None, indent=4, width=79, depth=None, *, 
          compact=False, ribbon_width=71, max_seq_len=1000, 
          sort_dict_keys=False, end='\n'):
    """
    Pretty print a Python value to stream (defaults to sys.stdout).
    
    Parameters:
    - object: The Python value to pretty print
    - stream: Output stream (defaults to sys.stdout)  
    - indent (int): Number of spaces to add for each nesting level (default: 4)
    - width (int): Soft maximum columns in output (default: 79)
    - depth (int): Maximum depth to print nested structures (default: None)
    - compact (bool): More compact output (default: False)
    - ribbon_width (int): Soft maximum columns after indenting (default: 71)
    - max_seq_len (int): Maximum sequence length before truncation (default: 1000)
    - sort_dict_keys (bool): Sort dictionary keys in output (default: False)
    - end (str): String appended after printing (default: '\n')
    """

Colored Pretty Printing

Pretty print Python objects with syntax highlighting and color support using Pygments for enhanced readability.

def cpprint(object, stream=None, indent=4, width=79, depth=None, *, 
           compact=False, ribbon_width=71, max_seq_len=1000, 
           sort_dict_keys=False, style=None, end='\n'):
    """
    Pretty print a Python value with color and syntax highlighting.
    
    Parameters:
    - object: The Python value to pretty print
    - stream: Output stream (defaults to sys.stdout)
    - indent (int): Number of spaces per nesting level (default: 4)
    - width (int): Soft maximum columns in output (default: 79)
    - depth (int): Maximum depth for nested structures (default: None)
    - compact (bool): More compact output (default: False)
    - ribbon_width (int): Soft maximum columns after indenting (default: 71)
    - max_seq_len (int): Maximum sequence length before truncation (default: 1000)
    - sort_dict_keys (bool): Sort dictionary keys in output (default: False)
    - style: Color style ('light', 'dark', or Style subclass) (default: auto-detected)
    - end (str): String appended after printing (default: '\n')
    """

String Formatting

Format Python objects as pretty printed strings without outputting to a stream, useful for capturing formatted output.

def pformat(object, indent=4, width=79, depth=None, *, 
           ribbon_width=71, max_seq_len=1000, compact=None, 
           sort_dict_keys=False) -> str:
    """
    Return pretty printed representation of object as a string.
    
    Parameters:
    - object: The Python value to format
    - indent (int): Number of spaces per nesting level (default: 4)
    - width (int): Soft maximum columns in output (default: 79)
    - depth (int): Maximum depth for nested structures (default: None)
    - ribbon_width (int): Soft maximum columns after indenting (default: 71)
    - max_seq_len (int): Maximum sequence length before truncation (default: 1000)
    - compact: Compatibility parameter (unused)
    - sort_dict_keys (bool): Sort dictionary keys in output (default: False)
    
    Returns:
    - str: Pretty printed representation without color
    """

Custom Repr Integration

Function for integrating prettyprinter with custom __repr__ methods, enabling classes to use prettyprinter for their string representation.

def pretty_repr(instance) -> str:
    """
    Function assignable to __repr__ method to use prettyprinter for repr output.
    
    Usage:
        class MyClass:
            __repr__ = pretty_repr
    
    Parameters:
    - instance: The instance being represented
    
    Returns:
    - str: Pretty printed representation of the instance
    
    Raises:
    - UserWarning: If no pretty printer is registered for the type
    """

PrettyPrinter Class

Class providing a pprint-compatible interface with configurable options, useful for maintaining consistent formatting settings across multiple print operations.

class PrettyPrinter:
    """
    Pretty printer class with pprint-compatible interface.
    
    Provides methods similar to pprint.PrettyPrinter but using
    prettyprinter's enhanced formatting capabilities.
    """
    
    def __init__(self, *args, **kwargs):
        """
        Initialize PrettyPrinter with formatting options.
        
        Parameters match those accepted by pprint() and cpprint().
        """
    
    def pprint(self, object):
        """Pretty print object using configured settings."""
    
    def pformat(self, object) -> str:
        """Format object as string using configured settings."""
    
    def isrecursive(self, object) -> bool:
        """Check if object contains recursive references."""
    
    def isreadable(self, object) -> bool:
        """Check if object's repr is readable."""
    
    def format(self, object):
        """Format method (not implemented - raises NotImplementedError)."""

Low-Level Functions

Core internal functions for converting Python values to documents and rendering output streams.

def python_to_sdocs(value, indent, width, depth, ribbon_width, 
                   max_seq_len, sort_dict_keys):
    """
    Convert Python value to structured documents for layout processing.
    
    This is the core function used internally by pprint, cpprint, and pformat
    to convert Python objects into a document representation that can be
    rendered with different output formats.
    
    Parameters:
    - value: Python object to convert
    - indent: indentation level per nesting level
    - width: target line width for layout
    - depth: maximum depth to traverse (None for unlimited)
    - ribbon_width: target width after indentation
    - max_seq_len: maximum sequence length before truncation
    - sort_dict_keys: whether to sort dictionary keys
    
    Returns:
    Iterator of structured documents ready for rendering
    """

def default_render_to_stream(stream, sdocs, newline='\n', separator=' '):
    """
    Render structured documents to a text stream without syntax highlighting.
    
    This function takes the output from python_to_sdocs and renders it as
    plain text to a stream object.
    
    Parameters:
    - stream: output stream (e.g., sys.stdout, StringIO)
    - sdocs: structured documents from python_to_sdocs
    - newline: string to use for line endings
    - separator: string to use between text elements
    """

Usage Examples

Basic Pretty Printing

from prettyprinter import pprint, cpprint, pformat

# Complex nested data
data = {
    'config': {
        'database': {
            'host': 'localhost',
            'port': 5432,
            'credentials': {'user': 'admin', 'pass': '***'}
        },
        'cache': {'redis_url': 'redis://localhost:6379', 'ttl': 3600}
    },
    'features': ['auth', 'logging', 'metrics'],
    'metadata': {'version': '1.2.3', 'build': 42}
}

# Plain text output
pprint(data, width=50)

# Colored output with custom style
cpprint(data, width=50, style='light')

# Get as string for further processing
formatted_string = pformat(data, width=40, sort_dict_keys=True)

Configuration Options

from prettyprinter import pprint

large_list = list(range(100))
deep_nested = {'a': {'b': {'c': {'d': {'e': 'deep'}}}}}

# Limit sequence length
pprint(large_list, max_seq_len=10)  # Shows first 10 items + truncation comment

# Limit nesting depth  
pprint(deep_nested, depth=3)  # Stops at depth 3 with "..."

# Custom indentation and width
pprint(data, indent=2, width=60, ribbon_width=50)

# Sort dictionary keys
pprint({'z': 1, 'a': 2, 'b': 3}, sort_dict_keys=True)

Using PrettyPrinter Class

from prettyprinter import PrettyPrinter

# Create configured printer
pp = PrettyPrinter(width=60, indent=2, sort_dict_keys=True)

# Use consistently across multiple objects
pp.pprint(data1)
pp.pprint(data2)

# Get formatted strings
formatted1 = pp.pformat(data1)
formatted2 = pp.pformat(data2)

Custom repr Integration

from prettyprinter import pretty_repr, register_pretty

class ComplexObject:
    def __init__(self, items):
        self.items = items
        self.metadata = {'created': '2024-01-01', 'count': len(items)}
    
    # Use prettyprinter for repr
    __repr__ = pretty_repr

# Register custom pretty printer for the class
@register_pretty(ComplexObject)
def pretty_complex_object(obj, ctx):
    return pretty_call(ctx, ComplexObject, obj.items)

# Now instances use prettyprinter for repr
obj = ComplexObject([1, 2, 3, 4, 5])
print(obj)  # Uses pretty_repr automatically

Install with Tessl CLI

npx tessl i tessl/pypi-prettyprinter

docs

comments.md

configuration.md

core-printing.md

document-system.md

extras.md

index.md

registration.md

tile.json