When switching from Python 2 to Python 3, the None
constant changes from type NoneType
to class NoneType
. In practice, this has no impact on day-to-day development, but I was curious to know if that meant I could now use typical class features like subclassing.
For those of you who don’t want to waste your time, the answer is: no, you can’t subclass NoneType
.
For everyone else, here’s the proof:
Python 2
These snippets were run on Python 2.7.17:
>>> type(None)
<type 'NoneType'>
>>> from types import NoneType
>>> class NoneTypeSubclass(NoneType):
... def some_function(self):
... return "Does this work?"
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
type 'NoneType' is not an acceptable base type
>>>
Python 3
These snippets were run on Python 3.8.1:
>>> type(None)
<class 'NoneType'>
>>> from types import NoneType
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'NoneType' from 'types' (/usr/lib/python3.8/types.py)
>>> class NoneTypeSubclass(type(None)):
... def some_function(self):
... return "Does this work?"
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type 'NoneType' is not an acceptable base type
And here’s the block from the source code that raises the error.
Oh well. I tried.