Skip to content

Commit 4d9c80a

Browse files
committed
Allow Any to match sequence patterns
1 parent 9274a07 commit 4d9c80a

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

mypy/checkpattern.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -713,6 +713,8 @@ def should_self_match(self, typ: Type) -> bool:
713713
return False
714714

715715
def can_match_sequence(self, typ: ProperType) -> bool:
716+
if isinstance(typ, AnyType):
717+
return True
716718
if isinstance(typ, UnionType):
717719
return any(self.can_match_sequence(get_proper_type(item)) for item in typ.items)
718720
for other in self.non_sequence_match_types:
@@ -763,6 +765,8 @@ def construct_sequence_child(self, outer_type: Type, inner_type: Type) -> Type:
763765
or class T(Sequence[Tuple[T, T]]), there is no way any of those can map to Sequence[str].
764766
"""
765767
proper_type = get_proper_type(outer_type)
768+
if isinstance(proper_type, AnyType):
769+
return outer_type
766770
if isinstance(proper_type, UnionType):
767771
types = [
768772
self.construct_sequence_child(item, inner_type)
@@ -772,7 +776,6 @@ def construct_sequence_child(self, outer_type: Type, inner_type: Type) -> Type:
772776
return make_simplified_union(types)
773777
sequence = self.chk.named_generic_type("typing.Sequence", [inner_type])
774778
if is_subtype(outer_type, self.chk.named_type("typing.Sequence")):
775-
proper_type = get_proper_type(outer_type)
776779
if isinstance(proper_type, TupleType):
777780
proper_type = tuple_fallback(proper_type)
778781
assert isinstance(proper_type, Instance)

test-data/unit/check-python310.test

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2439,3 +2439,35 @@ def foo(x: T) -> T:
24392439
return out
24402440

24412441
[builtins fixtures/isinstance.pyi]
2442+
2443+
[case testMatchSequenceReachableFromAny]
2444+
# flags: --warn-unreachable
2445+
from typing import Any
2446+
2447+
def maybe_list(d: Any) -> int:
2448+
match d:
2449+
case []:
2450+
return 0
2451+
case [[_]]:
2452+
return 1
2453+
case [_]:
2454+
return 1
2455+
case _:
2456+
return 2
2457+
2458+
def with_guard(d: Any) -> None:
2459+
match d:
2460+
case [s] if isinstance(s, str):
2461+
reveal_type(s) # N: Revealed type is "builtins.str"
2462+
match d:
2463+
case (s,) if isinstance(s, str):
2464+
reveal_type(s) # N: Revealed type is "builtins.str"
2465+
2466+
def nested_in_dict(d: dict[str, Any]) -> int:
2467+
match d:
2468+
case {"src": ["src"]}:
2469+
return 1
2470+
case _:
2471+
return 0
2472+
2473+
[builtins fixtures/dict.pyi]

0 commit comments

Comments
 (0)