How can i enable pretty print on the REPL by default?
Currently I do it by using pprint.pprint()
function.
>>> pprint.pprint(data)
{'SHIP_CATEGORY': '',
'SHIP_QUANTITY': 1,
'SHIP_SEPARATELY': 0,
'SHIP_SUPPLEMENT': 0,
'SHIP_SUPPLEMENT_ONCE': 0,
'THUMBNAIL': ''}
But I want pretty print by default
>>> data
{'SHIP_CATEGORY': '',
'SHIP_QUANTITY': 1,
'SHIP_SEPARATELY': 0,
'SHIP_SUPPLEMENT': 0,
'SHIP_SUPPLEMENT_ONCE': 0,
'THUMBNAIL': ''}
What have I tried?
I searched on google. Didn't found anything most result points to pprint
module
To use pprint, begin by importing the library at the top of your Python file. From here you can either use the . pprint() method or instantiate your own pprint object with PrettyPrinter() .
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.
The purpose is very simple, it is for printing anything in python. pprint() function also has similar functionality. But the only difference is in the way it prints complex data structures. The normal print() function prints the entire content in a single line.
Use sys.displayhook
import pprint
import sys
orig_displayhook = sys.displayhook
def myhook(value):
if value != None:
__builtins__._ = value
pprint.pprint(value)
__builtins__.pprint_on = lambda: setattr(sys, 'displayhook', myhook)
__builtins__.pprint_off = lambda: setattr(sys, 'displayhook', orig_displayhook)
Put Above code to PYTHONSTARTUP if you don't want type it every time you run interactive shell.
>>> data = dict.fromkeys(range(10))
>>> data
{0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
>>> pprint_on()
>>> data
{0: None,
1: None,
2: None,
3: None,
4: None,
5: None,
6: None,
7: None,
8: None,
9: None}
>>> pprint_off()
>>> data
{0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
Use IPython shell:
In [10]: data = {'SHIP_CATEGORY': '', 'SHIP_QUANTITY': 1, 'SHIP_SEPARATELY': 0, 'SHIP_SUPPLEMENT': 0, 'SHIP_SUPPLEMENT_ONCE': 0,}
In [11]: data
Out[11]:
{'SHIP_CATEGORY': '',
'SHIP_QUANTITY': 1,
'SHIP_SEPARATELY': 0,
'SHIP_SUPPLEMENT': 0,
'SHIP_SUPPLEMENT_ONCE': 0}
It also has an option --no-pprint
in case you want to disable this pretty printing.
IPython
shell also has features like tab-completion, multi-line paste, run shell commands etc. So, it is quite better than the normal python shell.
Based on falsetru's accepted answer, but in the form of a one-liner:
from pprint import pprint
import sys
sys.displayhook = lambda x: exec(['_=x; pprint(x)','pass'][x is None])
and to switch back (based on kyrill's comment):
sys.displayhook = sys.__displayhook__
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With