I have a Python script which processes a .txt file which contains report usage information. I\'d like to find a way to cleanly print the attributes of an object using pprint\'s
Dan's solution is just wrong, and Ismail's in incomplete.
__str__()
is not called, __repr__()
is called.__repr__()
should return a string, as pformat does.Here is an example
class S:
def __repr__(self):
from pprint import pformat
return pformat(vars(self), indent=4, width=1)
a = S()
a.b = 'bee'
a.c = {'cats': ['blacky', 'tiger'], 'dogs': ['rex', 'king'] }
a.d = S()
a.d.more_c = a.c
print(a)
This prints
{ 'b': 'bee',
'c': { 'cats': [ 'blacky',
'tiger'],
'dogs': [ 'rex',
'king']},
'd': { 'more_c': { 'cats': [ 'blacky',
'tiger'],
'dogs': [ 'rex',
'king']}}}
Which is not perfect, but passable.