[Python] Python type annotation for unique value representing 'not undefined'

Discussão em 'Python' iniciado por Stack, Fevereiro 12, 2025.

  1. Stack

    Stack Membro Participativo

    There is an idiom in Python to do something like,

    UNDEFINED = object()

    def do_something(value=UNDEFINED):
    if value is UNDEFINED:
    do1()
    else if value is None:
    do2()
    else:
    do3()


    The point being that None may be a valid value and UNDEFINED causes some other default behavior.

    The mypy signature would then be:

    def do_something(value=int|None|object):
    ...


    Which seems kind of pointless since everything is an object.

    Literal[UNDEFINED] isn't a valid, either.

    The best I can come up with so far is:

    class _Undefined:
    pass

    UNDEFINED = _Undefined()


    and

    def do_something(value=int|None|_Undefined):
    ...


    It's close, but introduces corner cases of someone passing _Undefined() (making a new instance) and means I'd be better off using isinstance rather than value is UNDEFINED as the old idiom encourages.

    Is there a new idiom emerging to do this with mypy and type annotations?

    Continue reading...

Compartilhe esta Página