tldr; I'm trying to use __repr__()
and pprint()
to pretty-print a custom python class to the terminal, but the output width remains the same no matter what width I pass to pprint()
. I have seen the question How can I make my class pretty printable in Python? - Stack Overflow, but it doesn't explain why the width isn't changing in my case, even though pprint() successfully prints my custom class.
Here's my __repr__()
function.
def __repr__(self):
output = 'task(' + repr(self.name) + ', ' + repr(self.subtasks) + ')'
return output
And here's the problem: when I try to test pprint()
with the following loop,
for width in [ 80, 20, 5 ]:
print('WIDTH =', width)
pprint(task_tree, width=width)
all outputs have the same width.
WIDTH = 80
task(root, [task(Top Level 1, [task(secondary, []), task(secondary b, []), task(secondary c, [])]), task(Top Level 2, []), task(Top Level 3, [])])
WIDTH = 20
task(root, [task(Top Level 1, [task(secondary, []), task(secondary b, []), task(secondary c, [])]), task(Top Level 2, []), task(Top Level 3, [])])
WIDTH = 5
task(root, [task(Top Level 1, [task(secondary, []), task(secondary b, []), task(secondary c, [])]), task(Top Level 2, []), task(Top Level 3, [])])
What could be going wrong? How should I modify my class' __repr__()
so that this works as expected, i.e. that pprint() prints representations of the class with widths of 80, 20, and 5 characters?
I based my approach on the following excerpt from pprint — Pretty-Print Data Structures — PyMOTW 3, where it's demonstrated how to use pprint()
with arbitrary classes.
Arbitrary Classes
The
PrettyPrinter
class used bypprint()
can also work with custom classes, if they define a__repr__()
method.pprint_arbitrary_object.py
from pprint import pprint class node: def __init__(self, name, contents=[]): self.name = name self.contents = contents[:] def __repr__(self): return ( 'node(' + repr(self.name) + ', ' + repr(self.contents) + ')' ) trees = [ node('node-1'), node('node-2', [node('node-2-1')]), node('node-3', [node('node-3-1')]), ] pprint(trees)
The representations of the nested objects are combined by the
PrettyPrinter
to return the full string representation.$ python3 pprint_arbitrary_object.py [node('node-1', []), node('node-2', [node('node-2-1', [])]), node('node-3', [node('node-3-1', [])])]