Search code examples
pythoncustomizationread-eval-print-loop

Default function in python shell


Entering an expression in Python shell outputs the repr() of the expression.

Is it possible to set this default function to some user defined function?


Solution

  • What you are looking for is sys.displayhook:

    sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session. The display of these values can be customized by assigning another one-argument function to sys.displayhook.

    Normal behaviour:

    >>> from datetime import datetime
    >>> datetime.now()
    datetime.datetime(2021, 11, 25, 15, 26, 1, 772968)
    

    then

    >>> import sys
    >>> def new_hook(value):
    ...   sys.stdout.write(str(value))
    ...   sys.stdout.write("\n")
    ... 
    >>> sys.displayhook = new_hook
    

    modified behaviour:

    >>> datetime.now()
    2021-11-25 15:26:14.177267