[Python] Should mypy infer type from Union options?

Discussão em 'Python' iniciado por Stack, Maio 26, 2025.

  1. Stack

    Stack Membro Participativo

    In the following code fn_int will only be called with an int as an argument, yet mypy complains I might be passing it a str (viceversa for fn_str).

    Is there something I'm missing here? Should/can I somehow narrow down the type before passing arguments to fn_int and fn_str?

    from typing import Union


    def fn_int(arg: int) -> None:
    print(arg)


    def fn_str(arg: str) -> None:
    print(arg)


    def fn(arg: Union[str, int]) -> None:

    if arg in range(4):
    fn_int(arg)
    elif arg == "str":
    fn_str(arg)
    else:
    raise ValueError


    > mypy mypy_test.py
    mypy_test.py:15: error: Argument 1 to "fn_int" has incompatible type "Union[str, int]"; expected "int" [arg-type]
    mypy_test.py:17: error: Argument 1 to "fn_str" has incompatible type "Union[str, int]"; expected "str" [arg-type]

    Continue reading...

Compartilhe esta Página