Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"
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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading