Reputation: 12697
Can I have pretty printed data output as in pprint.pprint
(new lines, indentation), but also shortened lists as in reprlib.repr
at the same time?
An ugly hack seems to be pprint(eval(reprlib.repr(data)))
, but is there a better way?
Upvotes: 7
Views: 652
Reputation: 11232
Since Python 3.12, reprlib.Repr
has an indent
option, which you can use to pretty-print. No need for the pprint
module.
>>> example = [1, 'spam', {'a': 2, 'b': 'spam eggs', 'c': {3: 4.5, 6: []}}, 'ham']
>>> from reprlib import Repr
>>> print(Repr(indent=4).repr(example))
[
1,
'spam',
{
'a': 2,
'b': 'spam eggs',
'c': {
3: 4.5,
6: [],
},
},
'ham',
]
>>> print(Repr(indent=4, maxlevel=1).repr(example))
[
1,
'spam',
{...},
'ham',
]
>>>
Source: https://docs.python.org/3/library/reprlib.html#reprlib.Repr.indent
Upvotes: 0
Reputation: 170450
You can change the way an object is printed by overriding the __repr__()
method on its class.
Python will allow you to override the repr of any class, so use it with care.
Upvotes: -2