Configuring the pretty printing for all objects in jupyter

Viewed 20

Jupyter seems to have some built-in pretty printing, via the lib.pretty submodule. However, I would like to configure the default printing by introducing a depth limit to the display, so that complex nested dictionaries are truncated. I can do this using Python's pprint.PrettyPrinter, but it's not clear to me how I can tell Jupyter to always use this printer when asked to display Python objects.

The ipython docs here describe how individual classes can be customized to have custom print logic, but I actually want my custom printer to be used for everything.

How can I do this with Jupyter?

1 Answers

It seems that you can register a formatter for object, which will affect everything that is displayed by Jupyter. However you have to do so separately for all the MIME types you want to target:

import pprint

for key in ["text/html", "text/markdown"]:
    get_ipython().display_formatter.formatters[key].for_type(
        object,
        lambda x: pprint.pformat(x, depth=2)
    )

You can of course change pprint.pformat to any pretty printing function you want.

Related