Welcome to PrettyPrinter’s documentation!¶
PrettyPrinter¶
Syntax-highlighting, declarative and composable pretty printer for Python 3.5+
pip install prettyprinter
- Drop in replacement for the standard library
pprint
: just renamepprint
toprettyprinter
in your imports. - Uses a modified Wadler-Leijen layout algorithm for optimal formatting
- Write pretty printers for your own types with a dead simple, declarative interface




Pretty print common Python values:
>>> from datetime import datetime
>>> from prettyprinter import pprint
>>> pprint({'beautiful output': datetime.now()})
{
'beautiful output': datetime.datetime(
year=2017,
month=12,
day=12,
hour=0,
minute=43,
second=4,
microsecond=752094
)
}
As well as your own, without any manual string formatting:
>>> class MyClass:
... def __init__(self, one, two):
... self.one = one
... self.two = two
>>> from prettyprinter import register_pretty, pretty_call
>>> @register_pretty(MyClass)
... def pretty_myclass(value, ctx):
... return pretty_call(ctx, MyClass, one=value.one, two=value.two)
>>> pprint(MyClass((1, 2, 3), {'a': 1, 'b': 2}))
MyClass(one=(1, 2, 3), two={'a': 1, 'b': 2})
>>> pprint({'beautiful output': datetime.now(), 'beautiful MyClass instance': MyClass((1, 2, 3), {'a': 1, 'b': 2})})
{
'beautiful MyClass instance': MyClass(
one=(1, 2, 3),
two={'a': 1, 'b': 2}
),
'beautiful output': datetime.datetime(
year=2017,
month=12,
day=12,
hour=0,
minute=44,
second=18,
microsecond=384219
)
}
Comes packaged with the following pretty printer definitions, which you can enable by calling prettyprinter.install_extras()
:
datetime
- (installed by default)enum
- (installed by default)pytz
- (installed by default)dataclasses
- any new class you create will be pretty printed automaticallyattrs
- pretty prints any new class you create withattrs
django
- pretty prints your Models and QuerySetsnumpy
- pretty prints numpy scalars with explicit typesrequests
- pretty prints Requests, Responses, Sessions, and more from therequests
library
- Free software: MIT license
- Documentation: Documentation.
User Guide¶
Usage¶
Install the package with pip
:
pip install prettyprinter
Then, instead of
from pprint import pprint
do
from prettyprinter import cpprint
for colored output. For colorless output, remove the c
prefix from the function name:
from prettyprinter import pprint
Usage in Python code¶
Call cpprint()
for colored output or pprint()
for uncolored output, just like pprint.pprint
:
>>> from prettyprinter import cpprint
>>> cpprint({'a': 1, 'b': 2})
{'a': 1, 'b': 2}
The default style is meant for a dark background. If you’re on a light background, or want to set your own theme, you may do so with set_default_style()
>>> from prettyprinter import set_default_style
>>> set_default_style('light')
Possible values are 'light'
, 'dark'
, and any subclass of pygments.styles.Style
.
Adding a pretty printer function to the global namespace¶
If you’re so inclined, you could add cpprint()
to the global namespace in your application so you can use it in a similar way as the built in print
function:
import builtins
import prettyprinter
builtins.pretty = prettyprinter.cpprint
pretty([1, 2, 3])
You’ll want to add this to a file that is executed during application initialization.
Usage with IPython¶
You can use prettyprinter with IPython so that values in the REPL will be printed with prettyprinter
using syntax highlighting. You need to call prettyprinter
initialization functions at the start of an IPython session, which IPython facilitates with profile startup files. To initialize prettyprinter in your default profile, add and edit a new startup file with the following commands:
touch "`ipython locate profile default`/startup/init_prettyprinter.py"
nano "`ipython locate profile default`/startup/init_prettyprinter.py"
The code in this file will be run upon entering the shell. Add these lines and comment out any extra packages you don’t need:
# Specify syntax higlighting theme in IPython;
# will be picked up by prettyprinter.
from pygments import styles
# For light terminal backgrounds.
from prettyprinter.color import GitHubLightStyle
ipy = get_ipython()
ipy.colors = 'LightBG'
ipy.highlighting_style = GitHubLightStyle
# For dark terminal background.
ipy = get_ipython()
ipy.colors = 'linux'
ipy.highlighting_style = styles.get_style_by_name('monokai')
import prettyprinter
prettyprinter.install_extras(
# Comment out any packages you are not using.
include=[
'ipython',
'ipython_repr_pretty',
'attrs',
'django',
'requests',
'dataclasses',
],
warn_on_error=True
)
Usage in the default Python shell¶
PrettyPrinter integrates with the default shell by overriding sys.displayhook
, so that values evaluated in the prompt will be printed using PrettyPrinter. The integration is set up as follows:
>>> from prettyprinter import install_extras
>>> install_extras(['python'])
>>> {'a': 1, 'b': 2}
{'a': 1, 'b': 2} # <- this will be colored when run in a terminal.
If you don’t want to run this every time you open a shell, create a Python startup file that executes the above statements and point the environment variable PYTHONSTARTUP
to that file in your shell initialization file (such as ~/.bashrc
), and rerun ~/.bashrc
to assign the correct PYTHONSTARTUP
value in your current shell session. Here’s a bash script to do that for you:
echo 'import prettyprinter; prettyprinter.install_extras(["python"])\n' >> ~/python_startup.py
echo "\nexport PYTHONSTARTUP=~/python_startup.py" >> ~/.bashrc
source ~/.bashrc
If you’re using a light background in your terminal, run this to add a line to the Python startup file to change the color theme PrettyPrinter uses:
echo '\nprettyprinter.set_default_style("light")' >> ~/python_startup.py
Then, after starting the python
shell,
python
values evaluated in the shell should be printed with PrettyPrinter without any other setup.
>>> {'a': 1, 'b': 2}
{'a': 1, 'b': 2} # <- the output should be colored when run in a terminal.
Pretty printing your own types¶
Given a custom class:
class MyClass(object):
def __init__(self, one, two):
self.one = one
self.two = two
You can register a pretty printer:
from prettyprinter import register_pretty, pretty_call
@register_pretty(MyClass)
def pretty_myclass(value, ctx):
return pretty_call(
ctx,
MyClass,
one=value.one,
two=value.two
)
To get an output like this with simple data:
>>> prettyprinter.pprint(MyClass(1, 2))
MyClass(one=1, two=2)
The real utility is in how nested data pretty printing is handled for you, and how the function call is broken to multiple lines for easier legibility:
>>> prettyprinter.pprint(MyClass({'abc': 1, 'defg': 2, 'hijk': 3}, [1, 2]))
MyClass(
one={
'abc': 1,
'defg': 2,
'hijk': 3
},
two=[1, 2]
)
@register_pretty
is a decorator that takes the type to register. Internally, functools.singledispatch
is used to handle dispatch to the correct pretty printer. This means that any subclasses will also use the same printer.
The decorated function must accept exactly two positional arguments:
value
to pretty print, andctx
, a context value.
In most cases, you don’t need need to do anything with the context, except pass it along in nested calls. It can be used to affect rendering of nested data.
The function must return a Doc
, which is either an instance of Doc
or a str
. pretty_call()
returns a Doc
that represents a function call. Given an arbitrary context ctx
pretty_call(ctx, round, 1.5)
Will be printed out as
round(1.5)
with syntax highlighting.
API Reference¶
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
tostream
, 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 toFalse
, 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 ofpygments.styles.Style
. If omitted, will use the default style. If the default style is not changed by the user withset_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
tostream
, which defaults tosys.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 toFalse
, 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 aspprint()
. The output is not colored.
-
prettyprinter.
pretty_repr
(instance)[source]¶ A function assignable to the
__repr__
dunder method, so that theprettyprinter
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_repr_pretty', 'python', 'numpy', 'requests', 'ipython', 'attrs', 'dataclasses', 'django'}), *, 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 theattrs
package.'dataclasses'
- automatically pretty prints classes created using thedataclasses
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.
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
andpredicate
may be supplied. That means thatpredicate
will be run on unregistered types only.The decorated function must accept exactly two positional arguments:
value
to pretty print, andctx
, 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()))
- type – the type to register the pretty printer for, or a
-
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 theargs
andkwargs
.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]¶
Meta¶
Credits¶
History¶
0.17.0 (2019-03-14)¶
- Add prettyprinter for numpy ndarrays. by @anntzer
- Add helper to apply default config. by @anntzer
- A number of docs and CI improvements: #43, #44, #45 .Thanks @anntzer
- Add support for functools.partialmethod. by @anntzer
- Fix typo in changelog. Thanks @Vlad-Shcherbina
0.16.0 (2019-02-27)¶
- Adds a new extra for numpy. The extra currently registers pretty printers for numpy scalar types. Enable it with
import prettyprinter; prettyprinter.install_extras(['numpy'])
. Thanks @anntzer - C-API named tuples are now automatically prettyprinted. C-API named tuples are returned from expressions such as
sys.flags
,time.strptime(...)
, andos.stat(...)
. The fieldname of each tuple element is annotated using a comment in the output.
0.15.0 (2019-02-25)¶
This release brings bugfixes, an enhancement to pathlib prettyprinting (thanks @anntzer ) and a nice performance boost. There was an redundant subtree call in a tree normalization procedure that caused exponential runtime, worsening quickly if data was highly nested. That extra call is now removed.
0.14.0 (2018-07-25)¶
Most likely no breaking changes.
- Added definitions for
pathlib
standard library module thanks to GitHub userRazerM
- Fixed unexpected error output inside Jupyter notebooks thanks to GitHub user
jdanbrown
- Fixed missing commas in
setup.py
requirements list
0.13.2 (2018-05-29)¶
No breaking changes.
- Fixed the dataclasses pretty printer that had regressed after changes to the dataclasses API. Fix was contributed by GitHub user
dangirsh
.
0.13.1 (2018-02-03)¶
No breaking changes.
- Fixed GH issue #17 where Django models showed an incorrect display name for fields with choices.
0.13.0 (2018-02-03)¶
No breaking changes.
- Added definitions for the
ast
standard library module thanks to GitHub userjohnnoone
.
0.12.0 (2018-01-22)¶
No breaking changes.
- Added a definition for classes that look like they were built with
collections.namedtuple
- If a pretty printer raises an exception, it is caught and emitted as a warning, and the default repr implementation will be used instead.
- Added definitions for
collections.ChainMap
,collections.defaultdict
,collections.deque
,functools.partial
, and for exception objects. - Made pretty printers for primitive types (dict, list, set, etc.) render a subclass constructor around them
0.11.0 (2018-01-20)¶
No breaking changes.
- Added Python 3.5 support
- Added
pretty_call_alt
function that doesn’t depend ondict
maintaining insertion order - Fixed bug in
set_default_config
where most configuration values were not updated - Added
get_default_config
0.10.1 (2018-01-10)¶
No breaking changes.
- Fixed regression with types.MappingProxyType not being properly registered.
0.10.0 (2018-01-09)¶
No breaking changes.
- Added support for deferred printer registration, where instead of a concrete type value, you can pass a qualified path to a type as a
str
toregister_pretty
. For an example, see the deferred printer registration for uuid.UUID
0.9.0 (2018-01-03)¶
No breaking changes.
- Added pretty printer definition for
types.MappingProxyType
thanks to GitHub user Cologler - Added support for
_repr_pretty_
in the extraipython_repr_pretty
.
0.8.1 (2018-01-01)¶
- Fixed issue #7 where having a
str
value for IPython’shighlighting_style
setting was not properly handled inprettyprinter
’s IPython integration, and raised an exception when trying to print data.
0.8.0 (2017-12-31)¶
Breaking changes:
- by default,
dict
keys are printed in the default order (insertion order in CPython 3.6+). Previously they were sorted like in thepprint
standard library module. To let the user control this, an additional keyword argumentsort_dict_keys
was added tocpprint
,pprint
, andpformat
. Pretty printer definitions can controldict
key sorting with thePrettyContext
instance passed to each pretty printer function.
Non-breaking changes:
- Improved performance of rendering colorized output by caching colors.
- Added
prettyprinter.pretty_repr
that is assignable to__repr__
dunder methods, so you don’t need to write it separately from the pretty printer definition. - Deprecated use of
PrettyContext.set
in favor of less misleadingPrettyContext.assoc
- Defined pretty printing for instances of
type
, i.e. classes. - Defined pretty printing for functions
0.7.0 (2017-12-23)¶
Breaking change: instances of lists, sets, frozensets, tuples and dicts will be truncated to 1000 elements by default when printing.
- Added pretty printing definitions for
dataclasses
- Improved performance of splitting strings to multiple lines by ~15%
- Added a maximum sequence length that applies to subclasses of lists, sets, frozensets, tuples and dicts. The default is 1000. There is a trailing comment that indicates the number of truncated elements. To remove truncation, you can set
max_seq_len
toNone
usingset_default_config
explained below. - Added ability to change the default global configuration using
set_default_config
. The functions accepts zero to many keyword arguments and replaces those values in the global configuration with the ones provided.
from prettyprinter import set_default_config
set_default_config(
style='dark',
max_seq_len=1000,
width=79,
ribbon_width=71,
depth=None,
)
0.6.0 (2017-12-21)¶
No backwards incompatible changes.
- Added pretty printer definitions for the
requests
library. To use it, include'requests'
in yourinstall_extras
call:prettyprinter.install_extras(include=['requests'])
.
0.5.0 (2017-12-21)¶
No backwards incompatible changes.
- Added integration for the default Python shell
- Wrote docs to explain integration with the default Python shell
- Check
install_extras
arguments for unknown extras
0.4.0 (2017-12-14)¶
- Revised
comment
to accept both normal Python values and Docs, and reversed the argument order to be more Pythonic
0.3.0 (2017-12-12)¶
- Add
set_default_style
function, improve docs on working with a light background
0.2.0 (2017-12-12)¶
- Numerous API changes and improvements.
0.1.0 (2017-12-07)¶
- First release on PyPI.