Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type narrowing after boolean exhaustion #11435

Closed
JulienPalard opened this issue Nov 2, 2021 · 1 comment
Closed

Type narrowing after boolean exhaustion #11435

JulienPalard opened this issue Nov 2, 2021 · 1 comment
Labels

Comments

@JulienPalard
Copy link
Member

JulienPalard commented Nov 2, 2021

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

@hauntsaninja
Copy link
Collaborator

This will be fixed by #10389

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants