Closed
Description
Feature
Given a Union[X, bool]
, after the exhaustion of "all" boolean possibilities, the type could be narrowed to X
, example:
from random import randint
from typing import Union
str_or_bool: Union[str, bool]
if randint(0, 1):
str_or_bool = "Hello"
else:
str_or_bool = False
if str_or_bool is True:
print("OK")
elif str_or_bool is False:
print("KO")
elif str_or_bool:
# If we land in this line, the type can't be bool, so the following expression is valid:
print(">" + str_or_bool)
I think similar "exhaustion narrowing" could be done with any type having a limited cardinality of values, like TypedDict keys, unions of literals, ... in if/elif/
chains and maybe in the match
statement?
Another example with Union of Union of Literals:
from random import randint
from typing import Union, Literal
Literal1 = Union[Literal["a", "b"]]
Literal2 = Union[Literal["c", "d"]]
thing: Union[Literal1, Literal2]
if randint(0, 1):
thing = "a"
else:
thing = "b"
if thing == "a":
print("OK")
elif thing == "b":
print("KO")
else:
reveal_type(thing) # Could be narrowed to Literal2
(But strangely in this case reveal_type shows nothing, is this an issue?)