Skip to content

Commit e1c03ab

Browse files
authored
Make ValuePattern non-exhaustive (#12751)
Changes behaviour of PatternChecker so that ValuePattern does not cover the entire (non-literal) type since it can catch only a single value. Fixes: #12545 Signed-off-by: Štěpán Horáček <xhorace2@fi.muni.cz>
1 parent 612074f commit e1c03ab

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

mypy/checkpattern.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from mypy.typeops import try_getting_str_literals_from_type, make_simplified_union, \
2424
coerce_to_literal
2525
from mypy.types import (
26-
ProperType, AnyType, TypeOfAny, Instance, Type, UninhabitedType, get_proper_type,
26+
LiteralType, ProperType, AnyType, TypeOfAny, Instance, Type, UninhabitedType, get_proper_type,
2727
TypedDictType, TupleType, NoneType, UnionType
2828
)
2929
from mypy.typevars import fill_typevars
@@ -183,6 +183,8 @@ def visit_value_pattern(self, o: ValuePattern) -> PatternType:
183183
o,
184184
default=current_type
185185
)
186+
if not isinstance(get_proper_type(narrowed_type), (LiteralType, UninhabitedType)):
187+
return PatternType(narrowed_type, UnionType.make_union([narrowed_type, rest_type]), {})
186188
return PatternType(narrowed_type, rest_type, {})
187189

188190
def visit_singleton_pattern(self, o: SingletonPattern) -> PatternType:

test-data/unit/check-python310.test

+15
Original file line numberDiff line numberDiff line change
@@ -1576,3 +1576,18 @@ def f(x: AST) -> None:
15761576
reveal_type(b) # N: Revealed type is "builtins.int"
15771577
reveal_type(c) # N: Revealed type is "builtins.str"
15781578
[builtins fixtures/tuple.pyi]
1579+
1580+
[case testMatchReachableDottedNames]
1581+
# flags: --warn-unreachable
1582+
class Consts:
1583+
BLANK = ""
1584+
SPECIAL = "asdf"
1585+
1586+
def test_func(test_str: str) -> str:
1587+
match test_str:
1588+
case Consts.BLANK:
1589+
return "blank"
1590+
case Consts.SPECIAL:
1591+
return "special"
1592+
case _:
1593+
return "other"

0 commit comments

Comments
 (0)