Feature
Given a Union[X, bool], after the exhaustion of "all" boolean possibilities, the type could be narrowed to X, example:
fromrandomimportrandintfromtypingimportUnionstr_or_bool: Union[str, bool]
ifrandint(0, 1):
str_or_bool="Hello"else:
str_or_bool=Falseifstr_or_boolisTrue:
print("OK")
elifstr_or_boolisFalse:
print("KO")
elifstr_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:
fromrandomimportrandintfromtypingimportUnion, LiteralLiteral1=Union[Literal["a", "b"]]
Literal2=Union[Literal["c", "d"]]
thing: Union[Literal1, Literal2]
ifrandint(0, 1):
thing="a"else:
thing="b"ifthing=="a":
print("OK")
elifthing=="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?)
Feature
Given a
Union[X, bool], after the exhaustion of "all" boolean possibilities, the type could be narrowed toX, example: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 thematchstatement?Another example with Union of Union of Literals:
(But strangely in this case reveal_type shows nothing, is this an issue?)