Python type hints: How to use Literal with strings to conform with mypy?


I want to restrict the possible input arguments by using typing.Literal.

The following code works just fine, however, mypy is complaining.

from typing import Literal

def literal_func(string_input: Literal["best", "worst"]) -> int:
    if string_input == "best":
        return 1
    elif string_input == "worst":
        return 0

literal_func(string_input="best")  # works just fine with mypy

# The following call leads to an error with mypy:
# error: Argument "string_input" to "literal_func" has incompatible type "str";
# expected "Literal['best', 'worst']"  [arg-type]

input_string = "best"

>Solution :

Unfortunately, mypy does not narrow the type of input_string to Literal["best"]. You can help it with a proper type annotation:

input_string: Literal["best"] = "best"

Perhaps worth mentioning that pyright works just fine with your example.

Alternatively, the same can be achieved by annotating the input_string as Final:

from typing import Final, Literal


input_string: Final = "best"

Leave a Reply Cancel reply