Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit from Python None

Tags:

python

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.

like image 800
RickyA Avatar asked Nov 27 '25 14:11

RickyA


1 Answers

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.

like image 174
OnesimusUnbound Avatar answered Dec 01 '25 01:12

OnesimusUnbound



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!