[Python] Python typing.Literal in a guarded context

Discussão em 'Python' iniciado por Stack, Julho 22, 2025.

  1. Stack

    Stack Membro Participativo

    The following MWE causes mypy to error.

    from typing import Literal

    def expects_literal(x: Literal["foo", "bar"]) -> None:
    print(f"{x=}")

    def fails_mypy_check(y: str) -> None:
    if y in ["foo", "bar"]:
    expects_literal(y)
    else:
    print("format incorrect")


    Results in:

    mwe.py:8: error: Argument 1 to "expects_literal" has incompatible type "str"; expected "Literal['foo', 'bar']" [arg-type]


    But the guard clause on line 7 ensures that y is one of the acceptable values. mypy docs call this an "exhaustiveness check" and imply it should be supported.


    Am I missing something?

    Continue reading...

Compartilhe esta Página