I have a variable x and a list of literals (say 0, 1, 2). I want to convert x to one of those literals: if x is in the list, I return it; otherwise I return a fallback value:
from typing import Literal, Set
Foo = Literal[0, 1, 2]
foos: Set[Foo] = {0, 1, 2}
def convert_to_foo(x: int) -> Foo:
if x in foos:
# x must have type Foo, yet this doesn't type check
y: Foo = x
return y
return 0
Unfortunately, this does not type check. Mypy returns the following message (see gist):
main.py:9: error: Incompatible types in assignment (expression has type "int", variable has type "Union[Literal[0], Literal[1], Literal[2]]")
If I belong to a list of Foos, then I am a Foo, right? I can't find an answer in the doc, can someone point me in the right direction?