Skip to content

Commit 96f8a99

Browse files
Fix narrowing of bool literal match subjects (#22202)
An expression such as `False` has type `bool` with a known value, stored as `last_known_value`. When narrowing against a bool literal pattern, `conditional_types()` expands the instance into `Literal[True] | Literal[False]` so that one member can be removed, but the expansion dropped the known value. As a result, `match False: case False:` left `Literal[True]` as the remaining type, the match was not considered exhaustive, and a following `case other` captured `Literal[False]` even though the subject could only be `False`. Keep the known value when expanding a sum type: if the instance already has a last known value, expand to that literal instead of the full union. The existing behaviour for plain `bool` and enum instances is unchanged.
1 parent 033f958 commit 96f8a99

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

‎mypy/typeops.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1153,6 +1153,12 @@ class Status(Enum):
11531153
if isinstance(typ, Instance) and (
11541154
target_fullname is None or typ.type.fullname == target_fullname
11551155
):
1156+
if typ.last_known_value is not None:
1157+
# The expression is already known to hold this specific value, so keep it: expanding
1158+
# to all members of the sum type would forget it and break narrowing, e.g. matching a
1159+
# ``False`` literal subject against ``case False`` would not be exhaustive.
1160+
return typ.last_known_value
1161+
11561162
if typ.type.fullname == "builtins.bool":
11571163
return UnionType([LiteralType(True, typ), LiteralType(False, typ)])
11581164

‎test-data/unit/check-python310.test‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,34 @@ def foo(m: bool, x: int):
5050
reveal_type(m) # N: Revealed type is "builtins.bool"
5151
[builtins fixtures/primitives.pyi]
5252

53+
[case testMatchBoolLiteralSubjectIsExhaustive]
54+
# flags: --strict-equality --warn-unreachable
55+
56+
def f() -> int:
57+
match False:
58+
case True:
59+
return 1 # E: Statement is unreachable
60+
case False:
61+
return 0
62+
63+
def g(b: bool) -> int:
64+
match b:
65+
case True:
66+
return 1
67+
case False:
68+
return 0
69+
70+
def h() -> int:
71+
match False:
72+
case True:
73+
return 1 # E: Statement is unreachable
74+
case False:
75+
return 0
76+
case other:
77+
reveal_type(other) # E: Statement is unreachable
78+
return 2
79+
[builtins fixtures/primitives.pyi]
80+
5381
[case testMatchLiteralPatternUnreachable]
5482
# flags: --strict-equality --warn-unreachable
5583
m: int

0 commit comments

Comments
 (0)