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

Question:

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"
literal_func(string_input=input_string)
Asked By: Andi

||

Answers:

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"
literal_func(string_input=input_string)

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"
literal_func(string_input=input_string)
Answered By: Paweł Rubin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.