Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display None values in IPython

By default, IPython doesn't seem to display None values:

In [1]: x = 1

In [2]: x
Out[2]: 1

In [3]: y = None

In [4]: y

I often end up writing y is None to be sure. How can I configure IPython to always show the value, even if it is None?

like image 892
Wilfred Hughes Avatar asked Dec 20 '22 02:12

Wilfred Hughes


1 Answers

This is deliberate, since all expressions return something, even if it is only None. You'd see nothing but None in your interpreter.

You can explicitly show the return value with repr() or str(), or by printing (which calls str() on results by default):

>>> y = None
>>> repr(y)
'None'
>>> str(y)
'None'
>>> print repr(y)
None
>>> print y
None

print repr() would be closest to what the interpreter does if an expression result is not None.

The regular Python interpreter uses sys.displayhook() to display interpreter expression results; the IPython interpreter uses it's own hook to do this, but this hook explicitly ignores None.

You can certainly use your own wrapper, the following hook delegates to a pre-existing hook and always displays None, regardless:

import sys

_chained_hook = sys.displayhook
def my_displayhook(res):
    _chained_hook(res)
    if res is None:
        sys.stdout.write('None\n')

sys.displayhook = my_displayhook
like image 149
Martijn Pieters Avatar answered Dec 26 '22 18:12

Martijn Pieters