python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.19k stars 2.78k forks source link

Literal typeguard #10028

Open tamuhey opened 3 years ago

tamuhey commented 3 years ago

Feature

Infer str is an instance of Literal based on code path:

from typing import Literal

def f(x: Literal["a", "b"]):
    ...

def g(x: str):
    if x == "a":
        ...
    elif x == "b":
        ...
    else:
        raise ValueError()
    f(x) # ERROR: "f" has incompatible type "str"; expected "Union[Literal['a'], Literal['b']]"

Mypy reports error for the above code, but x is actually an instance of Literal["a", "b"], because all values other than "a" or "b" raises ValueError. Pyright, one of type checkers, can infer this code has no problem.

JulienPalard commented 2 years ago

I think I just found a closely related example:

from typing import Literal

dest: Literal["tata", "tutu"]

for src in "tata", "tutu":
    dest = src  # error: Incompatible types in assignment (expression has type "str", variable has type "Literal['http', 'https']")

Don't mind me, I opened a specific issue for my example as it's not exactly the same thing (#12446).