Open
Description
Feature
When using typing.get_args()
to ensure that a given string is of a literal type, I would expect mypy to behave similarly than when isinstance()
checks are used.
Pitch
Take the following code:
from typing import Literal, TypeAlias, get_args
ExpectedUserInput: TypeAlias = Literal[
"these", "strings", "are", "expected", "user", "input"
]
def external_function(input: str) -> str:
if input not in get_args(ExpectedUserInput):
raise ValueError("Invalid input.")
return _internal_function(input)
def _internal_function(input: ExpectedUserInput) -> str:
return f"User input: {input}"
Mypy does not detect that the string must be of the correct type, since the code path is unreachable for an invalid value and outputs an error, requiring the use of casts even though the value is guaranteed to be of the correct type:
...: error: Argument 1 to "_internal_function" has incompatible type "str"; expected "Literal['these', 'strings', 'are', 'expected', 'user', 'input']" [arg-type]