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
docs.python.org › 3 › library › pprint.html
pprint — Data pretty printer
Source code: Lib/pprint.py The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted struc...
python - How to use pprint to print an object using the built-in __str__(self) method? - Stack Overflow
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 pprint(vars(object)) function. The script reads the file and creates instances of a Report class. More on stackoverflow.com
Print dataclasses with indendation levels?
You can try prettyprint, but there is no way to tell without an example. https://docs.python.org/3/library/pprint.html More on reddit.com
New Protocol for Pretty Printing
Looks pretty cool to me. dataclasses have this kind of repr thing built in, but it would be nice to have this tool if i were doing something else, to build them on my own. that said, your code above requires putting in the defaults twice. i bet you could automate the work inside __rich_repr__ by using inspect.signature, something like this: from inspect import signature from rich.repr import rich_repr @rich_repr class Bird: def __init__(self, name, eats=None, fly=True, extinct=False): self.name = name self.eats = list(eats) if eats else [] self.fly = fly self.extinct = extinct def __rich_repr__(self): for name, param in signature(Bird).parameters.items(): if param.default == param.empty: yield name, getattr(self, name) else: yield name, getattr(self, name), param.default if __name__ == "__main__": print(Bird("gull", eats=["fish", "chips", "ice cream", "sausage rolls"])) print(Bird("penguin", eats=["fish"], fly=False)) print(Bird("dodo", eats=["fruit"], fly=False, extinct=True)) More on reddit.com
Made a color pretty printer which auto-generates a label before the value.
Check out https://github.com/samuelcolvin/python-devtools More on reddit.com
Python Module of the Week
pymotw.com › 2 › pprint
pprint – Pretty-print data structures - Python Module of the Week
$ python pprint_pformat.py DEBUG Logging pformatted data DEBUG [(0, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H'}), (1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H'}), (2, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H'})] The PrettyPrinter class used by pprint() can also work with your own classes, if they define a __repr__() method.
Jython
jython.org › jython-old-sites › docs › library › pprint.html
8.18. pprint — Data pretty printer — Jython v2.5.2 documentation
The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable.
W3Schools
w3schools.com › python › ref_module_pprint.asp
Python pprint Module
The pprint module formats Python objects in a way that's easier for humans to read.
Top answer 1 of 6
40
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.
2 of 6
14
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.)
Python
docs.python.org › 2 › library › pprint.html
8.18. pprint — Data pretty printer — Python 2.7.18 documentation
July 19, 2020 - The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable.
Scaler
scaler.com › home › topics › python pprint module
Python Pprint Module - Scaler Topics
May 4, 2023 - Now, you can use the function pprint.pprint() to “pretty-print” your data. You can also create an object of the class PrettyPrinter() and customize it according to your requirements.
Read the Docs
stackless.readthedocs.io › en › 2.7-slp › library › pprint.html
8.18. pprint — Data pretty printer — Stackless-Python 2.7.15 documentation
>>> import pprint >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> stuff.insert(0, stuff[:]) >>> pp = pprint.PrettyPrinter(indent=4) >>> pp.pprint(stuff) [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'], 'spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', ... ('parrot', ('fresh fruit',)))))))) >>> pp = pprint.PrettyPrinter(depth=6) >>> pp.pprint(tup) ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...))))))) The PrettyPrinter class supports several derivative functions:
GeeksforGeeks
geeksforgeeks.org › pprint-data-pretty-printer-python
pprint : Data pretty printer in Python - GeeksforGeeks
This article is about a pretty useful built-in module in Python, pprint. The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a well-formatted and more readable way!
Published: October 6, 2023
Python
docs.python.org › 3.4 › library › pprint.html
8.11. pprint — Data pretty printer — Python 3.4.10 documentation
The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable.
TutorialsPoint
tutorialspoint.com › python_text_processing › python_pretty_prints.htm
Python Text Processing - Pretty Printing
Those data objects can represent ... module and after applying it. import pprint student_dict = {'Name': 'Tusar', 'Class': 'XII', ......
Note.nkmk.me
note.nkmk.me › home › python
Pretty-print in Python: pprint | note.nkmk.me
May 17, 2023 - s_normal = str(l) print(s_normal) # [{'Name': 'Alice XXX', 'Age': 40, 'Points': [80, 20]}, {'Name': 'Bob YYY', 'Age': 20, 'Points': [90, 10]}, {'Name': 'Charlie ZZZ', 'Age': 30, 'Points': [70, 30]}] print(type(s_normal)) # <class 'str'> ... You can use pprint.pformat() to get the output of pprint.pprint() as the string str.