Why is n
the exact same Object as None
?
The C implementation keeps a singleton instance. NoneType.__new__
is returning the singleton instance.
Why was the language designed such that n is the exact same Object as None
?
If there was not a singleton instance, then you could not rely on the check x is None
since the is
operator is based on identity. Although None == None
is also True
, it's possible to have x == None
be True
when x
is not actually None
. See this answer for an example.
How would one even implement this behavior in python?
You can implement this pattern by overridding __new__
. Here's a basic example:
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if Singleton._instance is None:
Singleton._instance = object.__new__(cls, *args, **kwargs)
return Singleton._instance
if __name__ == '__main__':
s1 = Singleton()
s2 = Singleton()
print 's1 is s2:', s1 is s2
print 'id(s1):', id(s1)
print 'id(s2):', id(s2)
Output:
s1 is s2: True
id(s1): 4506243152
id(s2): 4506243152
Of course this simple example doesn't make it impossible to create a second instance.