Pretty print by default in Python REPL Pretty print by default in Python REPL python python

Pretty print by default in Python REPL


Use sys.displayhook

import pprintimport sysorig_displayhook = sys.displayhookdef 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.

Usage:

>>> 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]: dataOut[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 pprintimport syssys.displayhook = lambda x: exec(['_=x; pprint(x)','pass'][x is None])

and to switch back (based on kyrill's comment):

sys.displayhook = sys.__displayhook__