Skip to content

Literal typeguard #10028

@tamuhey

Description

@tamuhey

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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions