Skip to content

Type narrowing after boolean exhaustion #11435

Description

@JulienPalard

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?)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions