4

Note: This question is about the mechanics of pprint and not asking about namedtuples. Namedtuples are used as a tangible example, but the question is not "how do I make namedtuple more beautiful for pprinting?"


What method does pprint call to display an object's data? How can I override this?

In this example, I would like to pretty print the named tuple d so that it prints one data element per line, similar to how the dict a is being printed.

>>> import pprint
>>> import collections

>>> a={'a': 'a'*40, 'b': 'b'*40}
>>> d=collections.namedtuple('D', 'a b')('a'*40, 'b'*40)

>>> # How do I make d print similarly to a?
>>> pprint.pprint(a)
{'a': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
 'b': 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'}
>>> pprint.pprint(d)
D(a='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', b='bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')
Mark Harrison
  • 297,451
  • 125
  • 333
  • 465
  • Possible duplicate: [Pretty print namedtuple](https://stackoverflow.com/q/30062384/4518341) – wjandrea Feb 15 '21 at 22:08
  • 1
    A bit of hack, but gets the job done: `pprint.pprint(d._asdict())` – rhurwitz Feb 15 '21 at 22:21
  • 2
    The key aspect here is really that [`PrettyPrinter`](https://github.com/python/cpython/blob/3.9/Lib/pprint.py#L103) defines all of that logic itself, i.e. it's not defined on the type. So subclassing is the way to go. – a_guest Feb 15 '21 at 22:24
  • @wjandrea, not a duplicate, I think... the question is about how pprint works, just using namedtuples as an example. Just IMHO! – Mark Harrison Feb 16 '21 at 02:48
  • The general one is [python - best way to implement custom pretty-printers - Stack Overflow](https://stackoverflow.com/questions/3258072/best-way-to-implement-custom-pretty-printers) (which includes "undocumented" ways to modify pprint, and a suggestion to use `pretty` instead) – user202729 Feb 16 '21 at 05:32
  • Assume that your actual question is "how to override" that should have it. Asking how it work internally... (I mean, just read its source code? Surely it handles some indentation logic, iterate through dict/list, etc.) – user202729 Feb 16 '21 at 05:34

0 Answers0