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

extras.mddocs/

Extras and Extensions

System for installing and managing third-party library integrations and extensions. The extras system provides specialized pretty printing support for popular Python libraries through a plugin architecture.

Capabilities

Extras Installation

Install pretty printing support for third-party libraries through the extras system.

def install_extras(include=ALL_EXTRAS, *, exclude=frozenset(), 
                  raise_on_error=False, warn_on_error=True):
    """
    Install pretty printer extras for third-party libraries.
    
    Parameters:
    - include: Iterable of extra names to install (default: all available)
    - exclude: Iterable of extra names to exclude from installation
    - raise_on_error (bool): Raise exceptions on import/install failures (default: False)
    - warn_on_error (bool): Show warnings on import/install failures (default: True)
    
    Notes:
    - Automatically handles missing dependencies gracefully
    - Each extra registers pretty printers for relevant library types
    - Safe to call multiple times - already installed extras are skipped
    """

ALL_EXTRAS: frozenset
    """
    Set of all available extra names:
    - 'attrs': Pretty printing for attrs-decorated classes
    - 'dataclasses': Pretty printing for dataclass instances  
    - 'django': Pretty printing for Django models and querysets
    - 'ipython': IPython shell integration
    - 'ipython_repr_pretty': Support for IPython _repr_pretty_ protocol
    - 'numpy': Pretty printing for NumPy arrays and scalars
    - 'python': Default Python shell integration
    - 'requests': Pretty printing for Requests library objects
    """

Available Extras

attrs Extra

Pretty printing support for classes created with the attrs library, displaying them as constructor calls with field values.

Installation: Requires attrs package Registration: Automatic for @attr.s decorated classes Output: ClassName(field1=value1, field2=value2)

dataclasses Extra

Pretty printing support for Python dataclasses, showing them as constructor calls with field values respecting repr=False settings.

Installation: Requires dataclasses module (Python 3.7+ or backport) Registration: Automatic for @dataclass decorated classes Output: ClassName(field1=value1, field2=value2)

django Extra

Pretty printing support for Django models and querysets with intelligent field selection and relationship handling.

Installation: Requires Django framework Registration: Automatic for Model and QuerySet subclasses Output:

  • Models: ModelName(pk=1, field1=value1, field2=value2)
  • QuerySets: <QuerySet [Model1, Model2, ...]>

ipython Extra

Integration with IPython shells to use prettyprinter as the default pretty printer in IPython environments.

Installation: Requires IPython Effect: Replaces IPython's default pretty printing with prettyprinter Usage: Automatic in IPython sessions after installation

ipython_repr_pretty Extra

Support for objects that implement IPython's _repr_pretty_ protocol, enabling integration with IPython's pretty printing system.

Installation: Requires IPython Registration: Automatic for objects with _repr_pretty_ method Effect: Uses object's custom _repr_pretty_ implementation

numpy Extra

Pretty printing support for NumPy arrays and scalars with explicit type information and array structure visualization.

Installation: Requires NumPy Registration: Automatic for numpy.ndarray and numpy scalar types Output:

  • Arrays: Structured visualization with shape and dtype info
  • Scalars: numpy.int64(42) style with explicit types

python Extra

Integration with the default Python REPL to use prettyprinter as the default pretty printer.

Installation: No additional dependencies Effect: Replaces Python's default pretty printing in REPL Usage: Automatic in Python interactive sessions

requests Extra

Pretty printing support for Requests library objects including requests, responses, and sessions.

Installation: Requires requests library Registration: Automatic for Request, Response, Session objects Output: Structured representation of HTTP objects with key information

Usage Examples

Basic Extras Installation

from prettyprinter import install_extras, pprint

# Install all available extras
install_extras()

# Install specific extras only
install_extras(include=['numpy', 'requests', 'dataclasses'])

# Install all except specific extras
install_extras(exclude=['django', 'ipython'])

# Install with error handling
install_extras(raise_on_error=True)  # Raise on any failures
install_extras(warn_on_error=False)  # Silent failures

Working with DataClasses

from prettyprinter import install_extras, pprint
from dataclasses import dataclass
from typing import List, Optional

# Install dataclasses support
install_extras(['dataclasses'])

@dataclass
class User:
    name: str
    age: int
    email: str
    active: bool = True
    tags: List[str] = None
    
    # This field won't appear in output
    _internal_id: int = 0, repr=False

@dataclass  
class Organization:
    name: str
    users: List[User]
    
user1 = User("Alice", 30, "alice@example.com", tags=["admin", "developer"])
user2 = User("Bob", 25, "bob@example.com")
org = Organization("Tech Corp", [user1, user2])

pprint(org)
# Organization(
#     name='Tech Corp',
#     users=[
#         User(name='Alice', age=30, email='alice@example.com', active=True, tags=['admin', 'developer']),
#         User(name='Bob', age=25, email='bob@example.com', active=True, tags=None)
#     ]
# )

Working with NumPy

from prettyprinter import install_extras, pprint
import numpy as np

# Install numpy support
install_extras(['numpy'])

# NumPy arrays
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
array_large = np.random.random((100, 100))
scalar = np.int64(42)

pprint([array_2d, scalar])
# Output shows array structure with dtype information
# and explicit scalar types

Working with Requests

from prettyprinter import install_extras, pprint
import requests

# Install requests support
install_extras(['requests'])

# HTTP objects are pretty printed with key information
response = requests.get('https://api.github.com/users/octocat')
session = requests.Session()
session.headers.update({'User-Agent': 'MyApp/1.0'})

pprint(response)
# Shows response status, headers, content info

pprint(session)
# Shows session configuration and state

Working with Django Models

from prettyprinter import install_extras, pprint
# Assuming Django is configured

# Install django support
install_extras(['django'])

# Django models and querysets are automatically handled
from myapp.models import User, Post

user = User.objects.get(id=1)
posts = Post.objects.filter(author=user)[:5]

pprint(user)
# User(id=1, username='alice', email='alice@example.com', ...)

pprint(posts)
# <QuerySet [Post(id=1, title='Hello World', ...), ...]>

IPython Integration

from prettyprinter import install_extras

# Install IPython integration
install_extras(['ipython'])

# Now all IPython pretty printing uses prettyprinter
# No additional code needed - works automatically

Custom Extra Development

# Example of creating a custom extra
# File: prettyprinter/extras/mylib.py

from prettyprinter import register_pretty, pretty_call

def install():
    """Install function called by install_extras()."""
    # Register pretty printers for mylib types
    pass

@register_pretty('mylib.MyClass')  # Deferred registration
def pretty_my_class(obj, ctx):
    return pretty_call(ctx, type(obj), obj.important_attr)

# Usage
from prettyprinter import install_extras
install_extras(['mylib'])  # Assumes mylib is in extras directory

Conditional Extras Installation

from prettyprinter import install_extras, ALL_EXTRAS
import importlib.util

def install_available_extras():
    """Install only extras for libraries that are available."""
    available_extras = []
    
    # Check which libraries are available
    extra_requirements = {
        'numpy': 'numpy',
        'requests': 'requests', 
        'django': 'django',
        'attrs': 'attr',
        'ipython': 'IPython'
    }
    
    for extra_name, module_name in extra_requirements.items():
        if importlib.util.find_spec(module_name):
            available_extras.append(extra_name)
    
    # Always include these (no external dependencies)
    available_extras.extend(['python', 'dataclasses', 'ipython_repr_pretty'])
    
    install_extras(include=available_extras)
    return available_extras

# Install only available extras
installed = install_available_extras()
print(f"Installed extras: {installed}")

Environment-Specific Extras

from prettyprinter import install_extras
import os

def setup_prettyprinter():
    """Configure prettyprinter based on environment."""
    
    base_extras = ['dataclasses', 'python']
    
    # Development environment
    if os.getenv('ENV') == 'development':
        extras = base_extras + ['numpy', 'requests', 'ipython']
        
    # Jupyter notebook environment  
    elif 'jupyter' in os.getenv('_', '').lower():
        extras = base_extras + ['numpy', 'ipython', 'ipython_repr_pretty']
        
    # Django application
    elif os.getenv('DJANGO_SETTINGS_MODULE'):
        extras = base_extras + ['django', 'requests']
        
    # Minimal production environment
    else:
        extras = base_extras
    
    install_extras(include=extras, warn_on_error=False)
    
setup_prettyprinter()

Extras Troubleshooting

from prettyprinter import install_extras, ALL_EXTRAS

def debug_extras_installation():
    """Debug extras installation issues."""
    
    print(f"Available extras: {sorted(ALL_EXTRAS)}")
    
    # Try installing each extra individually
    for extra in sorted(ALL_EXTRAS):
        try:
            install_extras(include=[extra], raise_on_error=True, warn_on_error=False)
            print(f"✓ {extra}: installed successfully")
        except Exception as e:
            print(f"✗ {extra}: failed - {e}")

debug_extras_installation()

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