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.- print normally indents only 1 character and tries to save lines. If you are trying to figure out structure, set the width low and indent high.
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.
Answer from Charles Merriam on Stack Overflowpython - How to use pprint to print an object using the built-in __str__(self) method? - Stack Overflow
python - How to pretty print nested dictionaries? - Stack Overflow
How to pretty print a BaseModel object?
Pretty print JSON from URL
Videos
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.- print normally indents only 1 character and tries to save lines. If you are trying to figure out structure, set the width low and indent high.
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.
pprint.pprint doesn't return a string; it actually does the printing (by default to stdout, but you can specify an output stream). So when you write print record, record.__str__() gets called, which calls pprint, which returns None. str(None) is 'None', and that gets printed, which is why you see None.
You should use pprint.pformat instead. (Alternatively, you can pass a StringIO instance to pprint.)
My first thought was that the JSON serializer is probably pretty good at nested dictionaries, so I'd cheat and use that:
>>> import json
>>> print(json.dumps({'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}},
... sort_keys=True, indent=4))
{
"a": 2,
"b": {
"x": 3,
"y": {
"t1": 4,
"t2": 5
}
}
}
I'm not sure how exactly you want the formatting to look like, but you could start with a function like this:
def pretty(d, indent=0):
for key, value in d.items():
print('\t' * indent + str(key))
if isinstance(value, dict):
pretty(value, indent+1)
else:
print('\t' * (indent+1) + str(value))