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 OverflowWhy Pretty Print?
python - Prettyprint to a file? - Stack Overflow
How can I make my class pretty printable in Python? - Stack Overflow
How to print a list in Python "nicely" - Stack Overflow
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.)
Hi all
I'm trying to understand the usefulness of Pretty Print.
In automate the boring stuff it was used a few times earlier in the book to make things look 'prettier', it didn't really look much better to me but I assumed this was down to taste.
Now I just saw an actual use-case for it later in the book and it seems like a very convoluted method.
After importing pretty print, the format function can be used to convert a list to a string which makes it easier to write to a text doc and subsequently reimport (apparently). But you can just put 'str' in front of the list to achieve the same thing, so I fail to see the point.
Any ideas?
:\
What you need is Pretty Print pprint module:
from pprint import pprint
# Build the tree somehow
with open('output.txt', 'wt') as out:
pprint(myTree, stream=out)
Another general-purpose alternative is Pretty Print's pformat() method, which creates a pretty string. You can then send that out to a file. For example:
import pprint
data = dict(a=1, b=2)
output_s = pprint.pformat(data)
# ^^^^^^^^^^^^^^^
with open('output.txt', 'w') as file:
file.write(output_s)
pprint does not look for any hooks. The pprint.PrettyPrinter uses a dispatch pattern instead; a series of methods on the class that are keyed on class.__repr__ references.
You can subclass pprint.PrettyPrinter to teach it about your class:
class YourPrettyPrinter(pprint.PrettyPrinter):
_dispatch = pprint.PrettyPrinter._dispatch.copy()
def _pprint_yourtype(self, object, stream, indent, allowance, context, level):
stream.write('YourType(')
self._format(object.foo, stream, indent, allowance + 1,
context, level)
self._format(object.bar, stream, indent, allowance + 1,
context, level)
stream.write(')')
_dispatch[YourType.__repr__] = _pprint_yourtype
then use the class directly to pretty print data containing YourType instances. Note that this is contingent on the type having their own custom __repr__ method!
You can also plug functions directly into the PrettyPrinter._dispatch dictionary; self is passed in explicitly. This is probably the better option for a 3rd-party library:
from pprint import PrettyPrinter
if isinstance(getattr(PrettyPrinter, '_dispatch'), dict):
# assume the dispatch table method still works
def pprint_ExtendedConfigParser(printer, object, stream, indent, allowance, context, level):
# pretty print it!
PrettyPrinter._dispactch[ExtendedConfigParser.__repr__] = pprint_ExtendedConfigParser
See the pprint module source code for how the other dispatch methods are written.
As always, single-underscore names like _dispatch are internal implementation details that can be altered in a future version. However, it is the best option you have here. The dispatch table was added in Python 3.5 and is present in at least Python 3.5 - 3.9 alpha.
You may want to look at rich, a third-party library that has some great pretty-printing capabilities, and supports hooks (__rich_repr__); see the documentation on customising pretty-printing.
It is not really a solution, but I usually just make objects serializable and pretty print them like this:
pprint(obj.dict())
» pip install prettyprint