Pprint() uses __repr__, although print() uses __str__

I am puzzled. With the name “pprint()”, shouldn’t pprint do something analogous to print()?

OR, more constructively

How do I make pprint behave more like print?

"""Looking into pprint"""
import pprint

class Skit:
    """Yes it is"""
    def __init__(self, topic):
        self.string_thing = topic
    def __repr__(self):
        return f"{__class__.__name__}('{self.string_thing}')"
    def __str__(self):
        return f"That's not an argument, it's just {self.string_thing}."

T = Skit("Fish Slapping")
print("print uses __str__")
print(T)
print("pprint uses __repr__")
pprint.pprint(T)

The first sentence of pprint’s documentation says it all:

The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter.

A string presentation of an arbitrary data structure that can be used as input to the interpreter–that describes repr rather than print.

So yeah pprint is really a misnomer–it would’ve been more aptly named prepr, though it’s kind of late/pointless to rename the module and function at this point in time.

1 Like

Thanks! I am new to python, and note that print has a storied history, and that correcting it caused a considerable fuss :slightly_smiling_face:. Perhaps pprint.prettiest() be added using the __str__form?

You can use a custom reprlib.Repr with type-specific repr methods instead:

import reprlib

class MyRepr(reprlib.Repr):
    def repr_Skit(self, obj, level):
        return str(obj)

aRepr = MyRepr(indent=' ' * 4)
print(aRepr.repr([Skit("Fish Slapping")]))

This outputs:

[
    That's not an argument, it's just Fish Slapping.,
]
2 Likes