My pprint module

alex_ber
3 min readMay 30, 2024

--

For a long time I was unhappy with default values that standard pprint module has (from pprint import pprint). So, I decided to change them as I like and not pass them every call to pprint.I’ve putted it to my AlexBerUtils project. See at the bottom references to another features in my library.

The source code you can found here. It is available as part of my AlexBerUtils s project.

You can install AlexBerUtils from PyPi:

python -m pip install -U alex-ber-utils

See here for more details explanation on how to install.

Enhancing Python’s pprint with my defaults

Intended Usage:

Instead of:

from pprint import pprint

use:

from alexber.utils.pprint import pprint

You can utilize any publicly available functions from pprint, including *.

One of the main changes is to set sort_dicts=False. From Python 3.7 onward, dictionary order is guaranteed to be the insertion order. This behavior was an implementation detail of CPython from version 3.6. As a result, the order of keys is now deterministic, eliminating the need to sort keys.

Default Settings:

  • indent: 4
  • width: 120
  • depth: None
  • stream: None
  • compact: False
  • sort_dicts: False
  • underscore_numbers: False

If a value is absent in your Python version’s pprint (for example, underscore_numbers was added only in Python 3.10), and you are using a lower version (e.g., Python 3.9), this argument will be safely ignored.

Example

Suppose you have some nested data structures and you’re using the munch library. This is not strictly necessary, as in most cases pprint will print what you intend. However, if you, like me, have data structures with AutoMunch, you will see AutoMunch printed out. To avoid this, you can use the unmunchify function.

from alexber.utils.pprint import pformat
from munch import unmunchify

s = '\n'+pformat(unmunchify(some_complex_ds))
logger.info(s)

Implementation details (only, if you’re interesting in)

Most of the pprint.pprint function uses pprint.PrettyPrinter under the cover. So first of all, I’m using

inspect.signature(_pprint.PrettyPrinter.__init__).parameters

to remove parameters, like underscore_numbers if you’re using Python <3.10.

Then I’m going over pprint.pprint.__all__ (it contains string, name of the objects that are publicly available from pprint.pprint) and if it is function I’m effectively changes it’s default according listed above, by using my inspects.update_function_defaults(). See My inspect module. If it is class, and I know, that the only class their is PrettyPrinter,I’m creating new subclass of it, and use it’s __init__ function to effectively update defaults.

For all object that I’m iterating I have it’s name and my new wrapped object.

this_module = importlib.import_module(__name__)

I’m getting this_module object and set as attribute all new wrapped object under the same name as in pprint.pprint.

--

--