Skip to content

Better narrows bool in if statements #11187

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -5307,9 +5307,10 @@ def conditional_type_map(expr: Expression,
return None, {}
else:
# we can only restrict when the type is precise, not bounded
proposed_precise_type = UnionType([type_range.item
for type_range in proposed_type_ranges
if not type_range.is_upper_bound])
proposed_precise_type = UnionType.make_union([
type_range.item
for type_range in proposed_type_ranges
if not type_range.is_upper_bound])
remaining_type = restrict_subtype_away(current_type, proposed_precise_type)
return {expr: proposed_type}, {expr: remaining_type}
else:
Expand Down
7 changes: 7 additions & 0 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1129,6 +1129,13 @@ def restrict_subtype_away(t: Type, s: Type, *, ignore_promotions: bool = False)
if (isinstance(get_proper_type(item), AnyType) or
not covers_at_runtime(item, s, ignore_promotions))]
return UnionType.make_union(new_items)
elif isinstance(t, Instance) and t.type.fullname == 'builtins.bool':
# Narrowing `bool` special case.
# When we got `bool` and `Literal[True]` / `Literal[False]`
# we return the inverse boolean value.
if isinstance(s, LiteralType):
return LiteralType(False, t) if s.value is True else LiteralType(True, t)
return t
else:
return t

Expand Down
20 changes: 20 additions & 0 deletions test-data/unit/check-narrowing.test
Original file line number Diff line number Diff line change
Expand Up @@ -1030,6 +1030,26 @@ else:

[builtins fixtures/primitives.pyi]

[case testNarrowingBoolLiteralIdentityCheck]
x: bool
if x is False:
reveal_type(x) # N: Revealed type is "Literal[False]"
else:
reveal_type(x) # N: Revealed type is "Literal[True]"

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]"

z: bool
if z: # TODO: this can be later emulated to be `z is True` in `mypy`
reveal_type(z) # N: Revealed type is "builtins.bool"
else:
reveal_type(z) # N: Revealed type is "builtins.bool"
[builtins fixtures/primitives.pyi]

[case testNarrowingTypedDictUsingEnumLiteral]
# flags: --python-version 3.6
from typing import Union
Expand Down