k_g
k_g

Reputation: 4463

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.

Upvotes: 2

Views: 74

Answers (1)

Ned Batchelder
Ned Batchelder

Reputation: 375854

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.

Upvotes: 4

Related Questions