Search code examples
pythonnonetyperepr

Can you create an object which acts like None when typed into the interpreter in Python?


Is it possible to create a class that has the following behavior?

>>> x = X()
>>> x
>>>

I tried the following

class X:
    def __repr__(self):
        return ""

which results in

>>> x = X()
>>> x

>>>

and also the following:

class X:
    def __repr__(self):
        return repr(None)

>>> x = X()
>>> x
None
>>>

and other ideas like returning None from __repr__ errors when you call repr on it, and deriving from NoneType just errors.


Solution

  • You can't make a value that behaves as you want, but you can change how the interactive prompt displays values. See sys.displayhook for how to customize the display.