I would like to create a class that inherits from None
.
I tried this:
class InvalidKeyNone(None):
pass
but that gives me:
TypeError: Error when calling the metaclass bases
cannot create 'NoneType' instances
What would be the correct solution that gives me a type that behaves exactly like None
but which I can type test?
foo = InvalidKeyNone()
print(type(foo))
>>> InvalidKeyNone
I want to do this because I am creating a selection scheme on Python datastructures:
bar = select(".foo.bar.[1].x", {"foo":{"bar":[{"x":1}, {"x":2}], "baz":3})
print(bar)
>> 2
And I want to be able to distinguish whether I get a None because the selected value is None or because the key was not found.
However, it must return a (ducktyped) None that behaves exactly like a None. No exceptions or custom type returning here.
I really want the default behavior to have it return a None when the key is not present.
None
is a constant, the sole value of NoneType
(which is in types
in v2.7 and v3.10+)
Anyway, when you try to inherit from NoneType
:
from types import NoneType # Python 2.7 or 3.10+
# NoneType = type(None) # Python 3.0-3.9
class InvalidKeyNone(NoneType):
pass
foo = InvalidKeyNone()
print(type(foo))
you'll get this error:
Python 2
TypeError: Error when calling the metaclass bases type 'NoneType' is not an acceptable base type
Python 3
TypeError: type 'NoneType' is not an acceptable base type
in short, you cannot inherit from NoneType
.