Skip to content

Better narrows bool in if statements - #11187

Closed
sobolevn wants to merge 1 commit into
python:masterfrom
sobolevn:better-bool-narrowing
Closed

Better narrows bool in if statements#11187
sobolevn wants to merge 1 commit into
python:masterfrom
sobolevn:better-bool-narrowing

Conversation

@sobolevn

Copy link
Copy Markdown
Member

For some reason previously bool was narrowed like this:

y: bool
if y is True:
    reveal_type(y)  # N: Revealed type is "Literal[True]"
else:
    reveal_type(y)  # N: Revealed type is "bool"

Which is not ideal, when we can do better:

y: bool
if y is True:
    reveal_type(y)  # N: Revealed type is "Literal[True]"
else:
    reveal_type(y)  # N: Revealed type is "Literal[False]"
@bluetech

Copy link
Copy Markdown
Contributor

I wonder how this relates to #6113 (which also points to an open PR #10389)?

@sobolevn

Copy link
Copy Markdown
Member Author

@bluetech yes, this looks like a very related issue. My approach is quite minimalistic compared to #10389 (which looks like a more full-featured solution).

Let's leave it @JukkaL to decide what to do.

@hauntsaninja

Copy link
Copy Markdown
Collaborator

My hesitation with this PR is that if bool_var is True is a somewhat unidiomatic check (I'd only recommend it for variables of type Optional[bool]), and I suspect solving the more general if bool_var case (as #10389 attempts to), will solve this case for free.

@sobolevn sobolevn closed this Sep 26, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants