attr_utils.pprinter

Pretty printing functions.

This module monkeypatches prettyprinter to disable a potentially undesirable behaviour of its singledispatch feature, where deferred types took precedence over resoled types.

It also changes the pretty print output for an enum.Enum to be the same as the Enum's __repr__.

Attention

This module has the following additional requirement:

prettyprinter==0.18.0

This can be installed as follows:

python -m pip install attr-utils[pprint]

Classes:

PrettyFormatter

typing.Protocol representing the pretty formatting functions decorated by register_pretty().

Data:

_PF

Invariant TypeVar bound to attr_utils.pprinter.PrettyFormatter.

Functions:

pretty_repr(​obj)

Add a pretty-printing __repr__ function to the decorated attrs class.

register_pretty(​[type, predicate])

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

protocol PrettyFormatter[source]

Bases: Protocol

typing.Protocol representing the pretty formatting functions decorated by register_pretty().

New in version 0.6.0.

This protocol is runtime checkable.

Classes that implement this protocol must have the following methods / attributes:

__call__(value, ctx)[source]

Call the function.

Parameters
  • value (Any) – The value to pretty print.

  • ctx (Any) – The context.

Return type

str

__non_callable_proto_members__ = {}

Type:    set

_PF = TypeVar(_PF, bound=PrettyFormatter)

Type:    TypeVar

Invariant TypeVar bound to attr_utils.pprinter.PrettyFormatter.

pretty_repr(obj)[source]

Add a pretty-printing __repr__ function to the decorated attrs class.

>>> import attr
>>> from attr_utils.pprinter import pretty_repr

>>> @pretty_repr
... @attr.s
... class Person(object):
...     name = attr.ib()

>>> repr(Person(name="Bob"))
Person(name='Bob')
Parameters

obj (Type)

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 (Union[Type, str, None]) – The type to register the pretty printer for, or a str to indicate the module and name, e.g. 'collections.Counter'. Default None.

  • predicate (Optional[Callable[[Any], bool]]) – A predicate function that takes one argument and returns a boolean indicating if the value should be handled by the registered pretty printer. Default None.

Only one of type and predicate may be supplied, and therefore predicate will only be called for unregistered types.

Return type

Callable[[~_PF], ~_PF]

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

from collections import OrderedDict
from attr_utils.pprinter import register_pretty
from prettyprinter import pretty_call

@register_pretty(OrderedDict)
def pretty_orderreddict(value, ctx):
    return pretty_call(ctx, OrderedDict, list(value.items()))