There is an improved and maintained Python 2.x/3.x port of "pretty" library in IPython: https://ipython.readthedocs.io/en/stable/api/generated/IPython.lib.pretty.html
Python 3.x: alternative pprint implementation
-
29-05-2022 - |
Frage
Standard pprint
module is nice when deals with lists, dicts and so on. But sometimes completely unusable with custom classes:
The only way to make it print usable information about an object of some class is to override
__repr__
, but what if my class already have nice,eval()
'able__repr__
which is not showing the information I want to see in pprint ouput?Ok, I will write print-oriented
__repr__
, but in this case it is impossible to pretty-print something inside my class:
.
class Data:
def __init__(self):
self.d = {...}
I can't pretty-print self.d
contents, I can return one-line representation only(at least without playing with stacktraces, etc).
- Overriding PrettyPrinter
is not an option, I dont want to do it every time I want to pretty-print the same class.
So... Is there any alternatives to pprint which allows to make a custom class pretty-printable?
Lösung
Andere Tipps
If the pretty module satisfies your needs, you can make it work with Python 3.
- Download and unpack the
pretty.py
file. Run 2to3 on it:
python -m lib2to3 -w pretty.py
Comment out the following lines:
569: types.DictProxyType: _dict_pprinter_factory('<dictproxy {', '}>'), 580: xrange: _repr_pprint,
Put the file near your script.
Import it as usual:
import pretty
for pretty printing you may be looking for __str__
instead of (or as well as) __repr__
e.g.
>>> import datetime
>>> now = datetime.datetime.now()
>>> print now
2013-05-19 13:00:34.085383
>>> print repr(now)
datetime.datetime(2013, 5, 19, 13, 0, 34, 85383)
You can create a generic solution that prints the contents of object fields by subclassing PrettyPrinter.
obj.__dict__
will give you a dictionary of all fields of obj
.
Or you can just use obj.__class__.__name__ + pformat(obj.__dict__)
.