I recently read somewhere that the special value None in python is a singleton object of its own class, specifically NoneType. This explained a lot, since most errors involving None in python produce AttributeErrors instead of some special "NoneError" or something.
Since all of these AttributeErrors reflected the attributes that NoneType lacked, I became intrigued by what attributes NoneType did have, if any.
I decided to look into this NoneType and learn more about it. I've always found the best way to learn about a new language feature is to use it, so I tried instantiating NoneType in IDLE:
>>> n = NoneType()
This produced an error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
n = NoneType()
NameError: name 'NoneType' is not defined
Confused, I inspected None to see if I'd gotten the type name correct. Sure enough,
>>> type(None)
<class 'NoneType'>
Now very confused, I did a quick google search. This revealed that for some reason NoneType was somehow removed in Python 3.
Well I though, ha ha! I can work around this by storing the type of None in a variable, since classes are objects in python. This seemed to work:
>>> NoneType = type(None)
>>> n = NoneType()
And when I printed n, I got pretty much what I was expecting:
>>> print(n)
None
But then this happened:
>>> n is None
True
And:
>>> id(n)
506768776
>>> id(None)
506768776
My variable n IS None. Not only the same type as None. It IS None. This is not what I expected.
I tried using dis to get more info on NoneType, but when I called
>>> dis.dis(type(None))
It produced no output.
I then then tried investigating the __new__ method, which several users had mentioned in the comments:
dis.dis(type(None).__new__)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
dis.dis(type(None).__new__)
File "C:\Python33\lib\dis.py", line 59, in dis
type(x).__name__)
TypeError: don't know how to disassemble builtin_function_or_method objects
>>>
More errors.
Here are my questions:
- Why is
nthe exact same Object asNone? - Why was the language designed such that
nis the exact same Object asNone? - How would one even implement this behavior in python?