[Python] Cannot use None as TypeVar constraint?

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    Using TypeVar one can annotate functions like:

    def f[T: (str, int)](x:T) -> T:
    if isinstance(x, int):
    return 0
    return x


    and type checkers will be happy. However it does not work for a None constraint.

    def f[T: (str, None)](x:T) -> T:
    if x is None:
    return None
    return x


    gives the error


    Type "None" is not assignable to type "T@f".
    ​

    Why is this not possible? Is there a way to achieve this with TypeVars or does one have to use overloads?

    The examples used to say return 'a', which would raise a valid error from the type checker. This was an oversight I made while trimming down the example for this question.

    Also it is indeed something that I ran into with pyright, not mypy (mypy doesn't complain).

    Continue reading...

Compartilhe esta Página