PrettyPrinter

0.18.0 · active · verified Mon Apr 13

PrettyPrinter is a Python library (version 0.18.0) that offers syntax-highlighting, declarative, and composable pretty printing for Python 3.5+ data structures. It aims to be a feature-rich alternative to Python's standard `pprint` module, providing improved readability, customizability, and integrations with other libraries. Its release cadence has been somewhat irregular, but the 0.18.0 version released in 2019 has been stable, suggesting a mature library.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic pretty-printing of a nested dictionary and how to define custom pretty-printing rules for your own classes using `@register_pretty`. It also notes how to enable shell integrations for a more persistent pretty-printing experience.

from prettyprinter import pprint, register_pretty, pretty_call

# Basic pretty-printing of a nested dictionary
data = {
    'name': 'PrettyPrinter Example',
    'details': {
        'id': 12345,
        'items': [
            {'item_id': 'A1', 'value': 100.5, 'tags': ['new', 'sale']},
            {'item_id': 'B2', 'value': 200, 'tags': ['old']},
            {'item_id': 'C3', 'value': 50.75, 'tags': []}
        ],
        'status': 'active'
    },
    'configs': [
        {'key': 'timeout', 'value': 30},
        {'key': 'retries', 'value': 5}
    ]
}

print('--- Standard print ---')
print(data)
print('\n--- PrettyPrinter output ---')
pprint(data)

# Custom pretty-printing for a user-defined class
class MyObject:
    def __init__(self, name, values):
        self.name = name
        self.values = values

@register_pretty(MyObject)
def pretty_my_object(value, ctx):
    return pretty_call(
        ctx,
        MyObject,
        name=value.name,
        values=value.values
    )

my_instance = MyObject('CustomItem', [{'x': 1, 'y': 2}, {'z': 3}])
print('\n--- Custom object pretty-printing ---')
pprint(my_instance)

# To enable shell integration (e.g., for `ipython` or default python shell):
# from prettyprinter import install_extras
# install_extras(['ipython']) # or ['python']
# {'a': 1, 'b': 2} # will now be pretty-printed in the shell

view raw JSON →