The pprint module has a function named pformat, for just that purpose.
From the documentation:
Return the formatted representation of object as a string. indent, width and depth will be passed to the PrettyPrinter constructor as formatting parameters.
Example:
>>> import pprint
>>> people = [
... {"first": "Brian", "last": "Kernighan"},
... {"first": "Dennis", "last": "Richie"},
... ]
>>> pprint.pformat(people, indent=4)
"[ { 'first': 'Brian', 'last': 'Kernighan'},\n { 'first': 'Dennis', 'last': 'Richie'}]"
Answer from SilentGhost on Stack OverflowThe pprint module has a function named pformat, for just that purpose.
From the documentation:
Return the formatted representation of object as a string. indent, width and depth will be passed to the PrettyPrinter constructor as formatting parameters.
Example:
>>> import pprint
>>> people = [
... {"first": "Brian", "last": "Kernighan"},
... {"first": "Dennis", "last": "Richie"},
... ]
>>> pprint.pformat(people, indent=4)
"[ { 'first': 'Brian', 'last': 'Kernighan'},\n { 'first': 'Dennis', 'last': 'Richie'}]"
Assuming you really do mean pprint from the pretty-print library, then you want
the pprint.pformat function.
If you just mean print, then you want str()
Videos
You should simply call the pformat function from the pprint module:
import pprint
s = pprint.pformat(aDict)
I sometimes use the json module for that:
In [1]: import json
In [2]: d = {'a':1, 'b':2, 'c':{'a':1}}
In [3]: s = json.dumps(d, indent=4)
In [4]: s
Out[4]: '{\n "a": 1, \n "c": {\n "a": 1\n }, \n "b": 2\n}'
In [5]: print s
{
"a": 1,
"c": {
"a": 1
},
"b": 2
}
I've recently documented a protocol in Rich to add pretty printing to arbitrary objects.
The problem was that containers like dicts, lists, sets etc could be formatted over multiple lines, but custom classes are limited to a string that can be generated from __repr__. The new protocol in Rich adds a __rich_repr__ method which allows an object to declare how it should be pretty printed.
Looking for feedback. Here are the docs.
Here's an example of a __rich_repr__ method.
And here's what it looks like when you pretty print a Bird instance: