API Reference

Top-level package for prettyprinter.

prettyprinter.cpprint(object, stream=UNSET, indent=UNSET, width=UNSET, depth=UNSET, *, compact=False, ribbon_width=UNSET, max_seq_len=UNSET, sort_dict_keys=UNSET, style=None, end='\n')[source]

Pretty print a Python value object to stream, which defaults to sys.stdout. The output will be colored and syntax highlighted.

Parameters:
  • indent – number of spaces to add for each level of nesting.
  • stream – the output stream, defaults to sys.stdout
  • width – a soft maximum allowed number of columns in the output, which the layout algorithm attempts to stay under.
  • depth – maximum depth to print nested structures
  • ribbon_width – a soft maximum allowed number of columns in the output, after indenting the line
  • max_seq_len – a maximum sequence length that applies to subclasses of lists, sets, frozensets, tuples and dicts. A trailing comment that indicates the number of truncated elements. Setting max_seq_len to None disables truncation.
  • sort_dict_keys – a bool value indicating if dict keys should be sorted in the output. Defaults to False, in which case the default order is used, which is the insertion order in CPython 3.6+.
  • style – one of 'light', 'dark' or a subclass of pygments.styles.Style. If omitted, will use the default style. If the default style is not changed by the user with set_default_style(), the default is 'dark'.
prettyprinter.pprint(object, stream=UNSET, indent=UNSET, width=UNSET, depth=UNSET, *, compact=False, ribbon_width=UNSET, max_seq_len=UNSET, sort_dict_keys=UNSET, end='\n')[source]

Pretty print a Python value object to stream, which defaults to sys.stdout. The output will not be colored.

Parameters:
  • indent – number of spaces to add for each level of nesting.
  • stream – the output stream, defaults to sys.stdout
  • width – a soft maximum allowed number of columns in the output, which the layout algorithm attempts to stay under.
  • depth – maximum depth to print nested structures
  • ribbon_width – a soft maximum allowed number of columns in the output, after indenting the line
  • max_seq_len – a maximum sequence length that applies to subclasses of lists, sets, frozensets, tuples and dicts. A trailing comment that indicates the number of truncated elements. Setting max_seq_len to None disables truncation.
  • sort_dict_keys – a bool value indicating if dict keys should be sorted in the output. Defaults to False, in which case the default order is used, which is the insertion order in CPython 3.6+.
prettyprinter.pformat(object, indent=UNSET, width=UNSET, depth=UNSET, *, ribbon_width=UNSET, max_seq_len=UNSET, compact=UNSET, sort_dict_keys=UNSET)[source]

Returns a pretty printed representation of the object as a str. Accepts the same parameters as pprint(). The output is not colored.

prettyprinter.pretty_repr(instance)[source]

A function assignable to the __repr__ dunder method, so that the prettyprinter definition for the type is used to provide repr output. Usage:

from prettyprinter import pretty_repr

class MyClass:
    __repr__ = pretty_repr
prettyprinter.install_extras(include=frozenset({'ipython', 'ipython_repr_pretty', 'django', 'python', 'dataclasses', 'numpy', 'attrs', 'requests'}), *, exclude=frozenset(), raise_on_error=False, warn_on_error=True)[source]

Installs extras.

Installing an extra means registering pretty printers for objects from third party libraries and/or enabling integrations with other python programs.

  • 'attrs' - automatically pretty prints classes created using the attrs package.
  • 'dataclasses' - automatically pretty prints classes created using the dataclasses module.
  • 'django' - automatically pretty prints Model and QuerySet subclasses defined in your
    Django apps.
  • numpy - automatically pretty prints numpy scalars with explicit types, and, for numpy>=1.14, numpy arrays.
  • 'requests' - automatically pretty prints Requests, Responses, Sessions, etc.
  • 'ipython' - makes prettyprinter the default printer in the IPython shell.
  • 'python' - makes prettyprinter the default printer in the default Python shell.
  • 'ipython_repr_pretty' - automatically prints objects that define a _repr_pretty_ method to integrate with IPython.lib.pretty.
Parameters:
  • include – an iterable of strs representing the extras to include. All extras are included by default.
  • exclude – an iterable of strs representing the extras to exclude.
prettyprinter.set_default_style(style)[source]

Sets default global style to be used by prettyprinter.cpprint.

Parameters:style – the style to set, either subclass of pygments.styles.Style or one of 'dark', 'light'
prettyprinter.set_default_config(*, style=UNSET, max_seq_len=UNSET, width=UNSET, ribbon_width=UNSET, depth=UNSET, sort_dict_keys=UNSET)[source]

Sets the default configuration values used when calling pprint, cpprint, or pformat, if those values weren’t explicitly provided. Only overrides the values provided in the keyword arguments.

prettyprinter.get_default_config()[source]

Returns a read-only view of the current configuration

prettyprinter.register_pretty(type=None, predicate=None)[source]

Returns a decorator that registers the decorated function as the pretty printer for instances of type.

Parameters:
  • type – the type to register the pretty printer for, or a str to indicate the module and name, e.g.: 'collections.Counter'.
  • predicate – a predicate function that takes one argument and returns a boolean indicating if the value should be handled by the registered pretty printer.

Only one of type and predicate may be supplied. That means that predicate will be run on unregistered types only.

The decorated function must accept exactly two positional arguments:

  • value to pretty print, and
  • ctx, a context value.

Here’s an example of the pretty printer for OrderedDict:

from collections import OrderedDict
from prettyprinter import register_pretty, pretty_call

@register_pretty(OrderedDict)
def pretty_orderreddict(value, ctx):
    return pretty_call(ctx, OrderedDict, list(value.items()))
prettyprinter.pretty_call(ctx, fn, *args, **kwargs)[source]

Returns a Doc that represents a function call to fn with the remaining positional and keyword arguments.

You can only use this function on Python 3.6+. On Python 3.5, the order of keyword arguments is not maintained, and you have to use pretty_call_alt().

Given an arbitrary context ctx,:

pretty_call(ctx, sorted, [7, 4, 5], reverse=True)

Will result in output:

sorted([7, 4, 5], reverse=True)

The layout algorithm will automatically break the call to multiple lines if needed:

sorted(
    [7, 4, 5],
    reverse=True
)

pretty_call automatically handles syntax highlighting.

Parameters:
  • ctx (prettyprinter.prettyprinter.PrettyContext) – a context value
  • fn – a callable
  • args – positional arguments to render to the call
  • kwargs – keyword arguments to render to the call
Returns:

Doc

prettyprinter.pretty_call_alt(ctx, fn, args=(), kwargs=())[source]

Returns a Doc that represents a function call to fn with the args and kwargs.

Given an arbitrary context ctx,:

pretty_call_alt(ctx, sorted, args=([7, 4, 5], ), kwargs=[('reverse', True)])

Will result in output:

sorted([7, 4, 5], reverse=True)

The layout algorithm will automatically break the call to multiple lines if needed:

sorted(
    [7, 4, 5],
    reverse=True
)

pretty_call_alt automatically handles syntax highlighting.

Parameters:
  • ctx (prettyprinter.prettyprinter.PrettyContext) – a context value
  • fn – a callable
  • args – a tuple of positional arguments to render to the call
  • kwargs – keyword arguments to render to the call. Either an instance of OrderedDict, or an iterable of two-tuples, where the first element is a str (key), and the second is the Python value for that keyword argument.
Returns:

Doc

prettyprinter.trailing_comment(value, comment_text)[source]

Annotates a value with a comment text, so that the comment will be rendered “trailing”, e.g. in place of the last element in a list, set or tuple, or after the last argument in a function.

This will force the rendering of value to be broken to multiple lines as Python does not have inline comments.

>>> trailing_comment(['value'], '...and more')
[
    'value',
    # ...and more
]
prettyprinter.comment(value, comment_text)[source]

Annotates a value or a Doc with a comment.

When printed by prettyprinter, the comment will be rendered next to the value or Doc.

prettyprinter.python_to_sdocs(value, indent, width, depth, ribbon_width, max_seq_len, sort_dict_keys)[source]
prettyprinter.default_render_to_stream(stream, sdocs, newline='\n', separator=' ')[source]
class prettyprinter.PrettyPrinter(*args, **kwargs)[source]

Bases: object

format(object)[source]
isreadable(object)[source]
isrecursive(object)[source]
pformat(object)[source]
pprint(object)[source]
prettyprinter.saferepr(object)[source]

Version of repr() which can handle recursive data structures.

prettyprinter.isreadable(object)[source]

Determine if saferepr(object) is readable by eval().

prettyprinter.isrecursive(object)[source]

Determine if object requires a recursive representation.