[Python] How to inherit from Python None

Discussão em 'Python' iniciado por Stack, Janeiro 2, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página