Debian Codegraph @

test-data/unit/check-python310.test

raw
1 -- Capture Pattern --
2
3 [case testMatchCapturePatternType]
4 # flags: --strict-equality --warn-unreachable
5 class A: ...
6 m: A
7
8 match m:
9 case a:
10 reveal_type(a) # N: Revealed type is "__main__.A"
11
12 -- Literal Pattern --
13
14 [case testMatchLiteralPatternNarrows]
15 # flags: --strict-equality --warn-unreachable
16 m: object
17
18 match m:
19 case 1:
20 reveal_type(m) # N: Revealed type is "Literal[1]"
21 case 2:
22 reveal_type(m) # N: Revealed type is "Literal[2]"
23 case other:
24 reveal_type(other) # N: Revealed type is "builtins.object"
25
26 [case testMatchLiteralPatternNarrows2]
27 # flags: --strict-equality --warn-unreachable
28 from typing import Any
29
30 m: Any
31
32 match m:
33 case 1:
34 reveal_type(m) # N: Revealed type is "Any"
35 case 2:
36 reveal_type(m) # N: Revealed type is "Any"
37 case other:
38 reveal_type(other) # N: Revealed type is "Any"
39
40 [case testMatchLiteralPatternBoolIntAlreadyNarrower]
41 # flags: --strict-equality --warn-unreachable
42
43 def foo(m: bool, x: int):
44 match m:
45 case 1:
46 reveal_type(m) # N: Revealed type is "builtins.bool"
47
48 match m:
49 case x:
50 reveal_type(m) # N: Revealed type is "builtins.bool"
51 [builtins fixtures/primitives.pyi]
52
53 [case testMatchLiteralPatternUnreachable]
54 # flags: --strict-equality --warn-unreachable
55 m: int
56
57 match m:
58 case "str":
59 reveal_type(m) # E: Statement is unreachable
60 [builtins fixtures/primitives.pyi]
61
62 -- Value Pattern --
63
64 [case testMatchValuePatternNarrows]
65 # flags: --strict-equality --warn-unreachable
66 import b
67 m: object
68
69 match m:
70 case b.b:
71 reveal_type(m) # N: Revealed type is "builtins.int"
72 [file b.py]
73 b: int
74
75 [case testMatchValuePatternAlreadyNarrower]
76 # flags: --strict-equality --warn-unreachable
77 import b
78 m: bool
79
80 match m:
81 case b.b:
82 reveal_type(m) # N: Revealed type is "builtins.bool"
83 [file b.py]
84 b: int
85
86 [case testMatchValuePatternIntersect]
87 # flags: --strict-equality --warn-unreachable
88 import b
89
90 class A: ...
91
92 def f(m: A) -> None:
93 match m:
94 case b.b:
95 reveal_type(m) # E: Statement is unreachable
96 [file b.py]
97 class B: ...
98 b: B
99
100 [case testMatchValuePatternUnreachable]
101 # flags: --strict-equality --warn-unreachable
102 import b
103
104 def f(m: int) -> None:
105 match m:
106 case b.b:
107 reveal_type(m) # E: Statement is unreachable
108 [file b.py]
109 b: str
110 [builtins fixtures/primitives.pyi]
111
112 -- Sequence Pattern --
113
114 [case testMatchSequencePatternCaptures]
115 # flags: --strict-equality --warn-unreachable
116 from typing import List
117 m: List[int]
118
119 match m:
120 case [a]:
121 reveal_type(a) # N: Revealed type is "builtins.int"
122 [builtins fixtures/list.pyi]
123
124 [case testMatchSequencePatternCapturesStarred]
125 # flags: --strict-equality --warn-unreachable
126 from typing import Sequence
127 m: Sequence[int]
128
129 match m:
130 case [a, *b]:
131 reveal_type(a) # N: Revealed type is "builtins.int"
132 reveal_type(b) # N: Revealed type is "builtins.list[builtins.int]"
133 [builtins fixtures/list.pyi]
134
135 [case testMatchSequencePatternNarrowsInner]
136 # flags: --strict-equality --warn-unreachable
137 from typing import Sequence
138 m: Sequence[object]
139
140 match m:
141 case [1, True]:
142 reveal_type(m) # N: Revealed type is "typing.Sequence[builtins.int]"
143
144 [case testMatchSequencePatternNarrowsOuter]
145 # flags: --strict-equality --warn-unreachable
146 from typing import Sequence
147 m: object
148
149 match m:
150 case [1, True]:
151 reveal_type(m) # N: Revealed type is "typing.Sequence[builtins.int]"
152
153 [case testMatchSequencePatternAlreadyNarrowerInner]
154 # flags: --strict-equality --warn-unreachable
155 from typing import Sequence
156 m: Sequence[bool]
157
158 match m:
159 case [1, True]:
160 reveal_type(m) # N: Revealed type is "typing.Sequence[builtins.bool]"
161
162 [case testMatchSequencePatternAlreadyNarrowerOuter]
163 # flags: --strict-equality --warn-unreachable
164 from typing import Sequence
165 m: Sequence[object]
166
167 match m:
168 case [1, True]:
169 reveal_type(m) # N: Revealed type is "typing.Sequence[builtins.int]"
170
171 [case testMatchSequencePatternAlreadyNarrowerBoth]
172 # flags: --strict-equality --warn-unreachable
173 from typing import Sequence
174 m: Sequence[bool]
175
176 match m:
177 case [1, True]:
178 reveal_type(m) # N: Revealed type is "typing.Sequence[builtins.bool]"
179
180 [case testMatchNestedSequencePatternNarrowsInner]
181 # flags: --strict-equality --warn-unreachable
182 from typing import Sequence
183 m: Sequence[Sequence[object]]
184
185 match m:
186 case [[1], [True]]:
187 reveal_type(m) # N: Revealed type is "typing.Sequence[typing.Sequence[builtins.int]]"
188
189 [case testMatchNestedSequencePatternNarrowsOuter]
190 # flags: --strict-equality --warn-unreachable
191 from typing import Sequence
192 m: object
193
194 match m:
195 case [[1], [True]]:
196 reveal_type(m) # N: Revealed type is "typing.Sequence[typing.Sequence[builtins.int]]"
197
198 [case testMatchSequencePatternDoesntNarrowInvariant]
199 # flags: --strict-equality --warn-unreachable
200 from typing import List
201 m: List[object]
202
203 match m:
204 case [1]:
205 reveal_type(m) # N: Revealed type is "builtins.list[builtins.object]"
206 [builtins fixtures/list.pyi]
207
208 [case testMatchSequencePatternMatches]
209 # flags: --strict-equality --warn-unreachable
210 import array, collections
211 from typing import Sequence, Iterable
212
213 m1: object
214 m2: Sequence[int]
215 m3: array.array[int]
216 m4: collections.deque[int]
217 m5: list[int]
218 m6: memoryview
219 m7: range
220 m8: tuple[int]
221
222 m9: str
223 m10: bytes
224 m11: bytearray
225
226 match m1:
227 case [a]:
228 reveal_type(a) # N: Revealed type is "builtins.object"
229
230 match m2:
231 case [b]:
232 reveal_type(b) # N: Revealed type is "builtins.int"
233
234 match m3:
235 case [c]:
236 reveal_type(c) # N: Revealed type is "builtins.int"
237
238 match m4:
239 case [d]:
240 reveal_type(d) # N: Revealed type is "builtins.int"
241
242 match m5:
243 case [e]:
244 reveal_type(e) # N: Revealed type is "builtins.int"
245
246 match m6:
247 case [f]:
248 reveal_type(f) # N: Revealed type is "builtins.int"
249
250 match m7:
251 case [g]:
252 reveal_type(g) # N: Revealed type is "builtins.int"
253
254 match m8:
255 case [h]:
256 reveal_type(h) # N: Revealed type is "builtins.int"
257
258 match m9:
259 case [i]:
260 reveal_type(i) # E: Statement is unreachable
261
262 match m10:
263 case [j]:
264 reveal_type(j) # E: Statement is unreachable
265
266 match m11:
267 case [k]:
268 reveal_type(k) # E: Statement is unreachable
269 [builtins fixtures/primitives.pyi]
270 [typing fixtures/typing-full.pyi]
271
272 [case testMatchSequencePatternCapturesTuple]
273 # flags: --strict-equality --warn-unreachable
274 from typing import Tuple
275 m: Tuple[int, str, bool]
276
277 match m:
278 case [a, b, c]:
279 reveal_type(a) # N: Revealed type is "builtins.int"
280 reveal_type(b) # N: Revealed type is "builtins.str"
281 reveal_type(c) # N: Revealed type is "builtins.bool"
282 reveal_type(m) # N: Revealed type is "tuple[builtins.int, builtins.str, builtins.bool]"
283 [builtins fixtures/list.pyi]
284
285 [case testMatchSequencePatternTupleTooLong]
286 # flags: --strict-equality --warn-unreachable
287 from typing import Tuple
288 m: Tuple[int, str]
289
290 match m:
291 case [a, b, c]:
292 reveal_type(a) # E: Statement is unreachable
293 reveal_type(b)
294 reveal_type(c)
295 [builtins fixtures/list.pyi]
296
297 [case testMatchSequencePatternTupleTooShort]
298 # flags: --strict-equality --warn-unreachable
299 from typing import Tuple
300 m: Tuple[int, str, bool]
301
302 match m:
303 case [a, b]:
304 reveal_type(a) # E: Statement is unreachable
305 reveal_type(b)
306 [builtins fixtures/list.pyi]
307
308 [case testMatchSequencePatternTupleNarrows]
309 # flags: --strict-equality --warn-unreachable
310 from typing import Tuple
311 m: Tuple[object, object]
312
313 match m:
314 case [1, "str"]:
315 reveal_type(m) # N: Revealed type is "tuple[Literal[1], Literal['str']]"
316 [builtins fixtures/list.pyi]
317
318 [case testMatchSequencePatternTupleStarred]
319 # flags: --strict-equality --warn-unreachable
320 from typing import Tuple
321 m: Tuple[int, str, bool]
322
323 match m:
324 case [a, *b, c]:
325 reveal_type(a) # N: Revealed type is "builtins.int"
326 reveal_type(b) # N: Revealed type is "builtins.list[builtins.str]"
327 reveal_type(c) # N: Revealed type is "builtins.bool"
328 reveal_type(m) # N: Revealed type is "tuple[builtins.int, builtins.str, builtins.bool]"
329 [builtins fixtures/list.pyi]
330
331 [case testMatchSequencePatternTupleStarredUnion]
332 # flags: --strict-equality --warn-unreachable
333 from typing import Tuple
334 m: Tuple[int, str, float, bool]
335
336 match m:
337 case [a, *b, c]:
338 reveal_type(a) # N: Revealed type is "builtins.int"
339 reveal_type(b) # N: Revealed type is "builtins.list[builtins.str | builtins.float]"
340 reveal_type(c) # N: Revealed type is "builtins.bool"
341 reveal_type(m) # N: Revealed type is "tuple[builtins.int, builtins.str, builtins.float, builtins.bool]"
342 [builtins fixtures/list.pyi]
343
344 [case testMatchSequencePatternTupleStarredTooShort]
345 # flags: --strict-equality --warn-unreachable
346 from typing import Tuple
347 m: Tuple[int]
348 reveal_type(m) # N: Revealed type is "tuple[builtins.int]"
349
350 match m:
351 case [a, *b, c]:
352 reveal_type(a) # E: Statement is unreachable
353 reveal_type(b)
354 reveal_type(c)
355 [builtins fixtures/list.pyi]
356
357 [case testMatchNonMatchingSequencePattern]
358 # flags: --strict-equality --warn-unreachable
359 from typing import List
360
361 x: List[int]
362 match x:
363 case [str()]:
364 pass
365
366 [case testMatchSequencePatternWithTypeObject]
367 # flags: --strict-equality --warn-unreachable
368 class Example:
369 __match_args__ = ("value",)
370 def __init__(self, value: str) -> None:
371 self.value = value
372
373 SubClass: type[Example]
374
375 match [SubClass("a"), SubClass("b")]:
376 case [SubClass(value), *rest]:
377 reveal_type(value) # N: Revealed type is "builtins.str"
378 reveal_type(rest) # N: Revealed type is "builtins.list[__main__.Example]"
379
380 [builtins fixtures/tuple.pyi]
381
382 # Narrowing union-based values via a literal pattern on an indexed/attribute subject
383 # -------------------------------------------------------------------------------
384 # Literal patterns against a union of types can be used to narrow the subject
385 # itself, not just the expression being matched. Previously, the patterns below
386 # failed to narrow the `d` variable, leading to errors for missing members; we
387 # now propagate the type information up to the parent.
388
389 [case testMatchNarrowingUnionTypedDictViaIndex]
390 # flags: --strict-equality --warn-unreachable
391 from typing import Literal, TypedDict
392
393 class A(TypedDict):
394 tag: Literal["a"]
395 name: str
396
397 class B(TypedDict):
398 tag: Literal["b"]
399 num: int
400
401 d: A | B
402 match d["tag"]:
403 case "a":
404 reveal_type(d) # N: Revealed type is "TypedDict('__main__.A', {'tag': Literal['a'], 'name': builtins.str})"
405 reveal_type(d["name"]) # N: Revealed type is "builtins.str"
406 case "b":
407 reveal_type(d) # N: Revealed type is "TypedDict('__main__.B', {'tag': Literal['b'], 'num': builtins.int})"
408 reveal_type(d["num"]) # N: Revealed type is "builtins.int"
409 [typing fixtures/typing-typeddict.pyi]
410
411 [case testMatchNarrowingUnionClassViaAttribute]
412 # flags: --strict-equality --warn-unreachable
413 from typing import Literal
414
415 class A:
416 tag: Literal["a"]
417 name: str
418
419 class B:
420 tag: Literal["b"]
421 num: int
422
423 d: A | B
424 match d.tag:
425 case "a":
426 reveal_type(d) # N: Revealed type is "__main__.A"
427 reveal_type(d.name) # N: Revealed type is "builtins.str"
428 case "b":
429 reveal_type(d) # N: Revealed type is "__main__.B"
430 reveal_type(d.num) # N: Revealed type is "builtins.int"
431
432 [case testMatchSequenceUnion]
433 # flags: --strict-equality --warn-unreachable
434 from typing import List, Union
435 m: Union[List[List[str]], str]
436
437 match m:
438 case [list(['str'])]:
439 reveal_type(m) # N: Revealed type is "builtins.list[builtins.list[builtins.str]]"
440 [builtins fixtures/list.pyi]
441
442 [case testMatchSequencePatternNarrowSubjectItems]
443 # flags: --strict-equality --warn-unreachable
444 m: int
445 n: str
446 o: bool
447
448 match m, n, o:
449 case [3, "foo", True]:
450 reveal_type(m) # N: Revealed type is "Literal[3]"
451 reveal_type(n) # N: Revealed type is "Literal['foo']"
452 reveal_type(o) # N: Revealed type is "Literal[True]"
453 case [a, b, c]:
454 reveal_type(m) # N: Revealed type is "builtins.int"
455 reveal_type(n) # N: Revealed type is "builtins.str"
456 reveal_type(o) # N: Revealed type is "builtins.bool"
457
458 reveal_type(m) # N: Revealed type is "builtins.int"
459 reveal_type(n) # N: Revealed type is "builtins.str"
460 reveal_type(o) # N: Revealed type is "builtins.bool"
461 [builtins fixtures/tuple.pyi]
462
463 [case testMatchSequencePatternNarrowSubjectItemsRecursive]
464 # flags: --strict-equality --warn-unreachable
465 m: int
466 n: int
467 o: int
468 p: int
469 q: int
470 r: int
471
472 match m, (n, o), (p, (q, r)):
473 case [0, [1, 2], [3, [4, 5]]]:
474 reveal_type(m) # N: Revealed type is "Literal[0]"
475 reveal_type(n) # N: Revealed type is "Literal[1]"
476 reveal_type(o) # N: Revealed type is "Literal[2]"
477 reveal_type(p) # N: Revealed type is "Literal[3]"
478 reveal_type(q) # N: Revealed type is "Literal[4]"
479 reveal_type(r) # N: Revealed type is "Literal[5]"
480 [builtins fixtures/tuple.pyi]
481
482 [case testMatchSequencePatternSequencesLengthMismatchNoNarrowing]
483 # flags: --strict-equality --warn-unreachable
484 m: int
485 n: str
486 o: bool
487
488 match m, n, o:
489 case [3, "foo"]:
490 pass # E: Statement is unreachable
491 case [3, "foo", True, True]:
492 pass # E: Statement is unreachable
493 [builtins fixtures/tuple.pyi]
494
495 [case testMatchSequencePatternSequencesLengthMismatchNoNarrowingRecursive]
496 # flags: --strict-equality --warn-unreachable
497 m: int
498 n: int
499 o: int
500
501 match m, (n, o):
502 case [0]:
503 pass # E: Statement is unreachable
504 case [0, 1, [2]]:
505 pass # E: Statement is unreachable
506 case [0, [1]]:
507 pass # E: Statement is unreachable
508 case [0, [1, 2, 3]]:
509 pass # E: Statement is unreachable
510 [builtins fixtures/tuple.pyi]
511
512 -- Mapping Pattern --
513
514 [case testMatchMappingPatternCaptures]
515 # flags: --strict-equality --warn-unreachable
516 from typing import Dict
517 import b
518 m: Dict[str, int]
519
520 match m:
521 case {"key": v}:
522 reveal_type(v) # N: Revealed type is "builtins.int"
523 case {b.b: v2}:
524 reveal_type(v2) # N: Revealed type is "builtins.int"
525 [file b.py]
526 b: str
527 [builtins fixtures/dict.pyi]
528
529 [case testMatchMappingPatternCapturesWrongKeyType]
530 # flags: --strict-equality --warn-unreachable
531 # This is not actually unreachable, as a subclass of dict could accept keys with different types
532 from typing import Dict
533 import b
534 m: Dict[str, int]
535
536 match m:
537 case {1: v}:
538 reveal_type(v) # N: Revealed type is "builtins.int"
539 case {b.b: v2}:
540 reveal_type(v2) # N: Revealed type is "builtins.int"
541 [file b.py]
542 b: int
543 [builtins fixtures/dict.pyi]
544
545 [case testMatchMappingPatternCapturesTypedDict]
546 # flags: --strict-equality --warn-unreachable
547 from typing import TypedDict
548
549 class A(TypedDict):
550 a: str
551 b: int
552
553 m: A
554
555 match m:
556 case {"a": v}:
557 reveal_type(v) # N: Revealed type is "builtins.str"
558 case {"b": v2}:
559 reveal_type(v2) # N: Revealed type is "builtins.int"
560 case {"a": v3, "b": v4}:
561 reveal_type(v3) # N: Revealed type is "builtins.str"
562 reveal_type(v4) # N: Revealed type is "builtins.int"
563 case {"o": v5}:
564 reveal_type(v5) # N: Revealed type is "builtins.object"
565 [typing fixtures/typing-typeddict.pyi]
566
567 [case testMatchMappingPatternCapturesTypedDictWithLiteral]
568 # flags: --strict-equality --warn-unreachable
569 from typing import TypedDict
570 import b
571
572 class A(TypedDict):
573 a: str
574 b: int
575
576 m: A
577
578 match m:
579 case {b.a: v}:
580 reveal_type(v) # N: Revealed type is "builtins.str"
581 case {b.b: v2}:
582 reveal_type(v2) # N: Revealed type is "builtins.int"
583 case {b.a: v3, b.b: v4}:
584 reveal_type(v3) # N: Revealed type is "builtins.str"
585 reveal_type(v4) # N: Revealed type is "builtins.int"
586 case {b.o: v5}:
587 reveal_type(v5) # N: Revealed type is "builtins.object"
588 [file b.py]
589 from typing import Final, Literal
590 a: Final = "a"
591 b: Literal["b"] = "b"
592 o: Final[str] = "o"
593 [typing fixtures/typing-typeddict.pyi]
594
595 [case testMatchMappingPatternCapturesTypedDictWithNonLiteral]
596 # flags: --strict-equality --warn-unreachable
597 from typing import TypedDict
598 import b
599
600 class A(TypedDict):
601 a: str
602 b: int
603
604 m: A
605
606 match m:
607 case {b.a: v}:
608 reveal_type(v) # N: Revealed type is "builtins.object"
609 [file b.py]
610 from typing import Final, Literal
611 a: str
612 [typing fixtures/typing-typeddict.pyi]
613
614 [case testMatchMappingPatternCapturesTypedDictUnreachable]
615 # flags: --strict-equality --warn-unreachable
616 # TypedDict keys are always str, so this is actually unreachable
617 from typing import TypedDict
618 import b
619
620 class A(TypedDict):
621 a: str
622 b: int
623
624 m: A
625
626 match m:
627 case {1: v}:
628 reveal_type(v) # E: Statement is unreachable
629 case {b.b: v2}:
630 reveal_type(v2) # E: Statement is unreachable
631 [file b.py]
632 b: int
633 [typing fixtures/typing-typeddict.pyi]
634
635 [case testMatchMappingPatternCaptureRest]
636 # flags: --strict-equality --warn-unreachable
637 m: object
638
639 match m:
640 case {'k': 1, **r}:
641 reveal_type(r) # N: Revealed type is "builtins.dict[builtins.object, builtins.object]"
642 [builtins fixtures/dict.pyi]
643
644 [case testMatchMappingPatternCaptureRestFromMapping]
645 # flags: --strict-equality --warn-unreachable
646 from typing import Mapping
647
648 m: Mapping[str, int]
649
650 match m:
651 case {'k': 1, **r}:
652 reveal_type(r) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
653 [builtins fixtures/dict.pyi]
654
655 [case testMatchMappingPatternNarrowing]
656 # flags: --strict-equality --warn-unreachable
657 from typing import Mapping, Sequence
658
659 def f1(x: dict[str, str] | list[str] | str) -> None:
660 match x:
661 case {}:
662 reveal_type(x) # N: Revealed type is "builtins.dict[builtins.str, builtins.str]"
663 case [*_]:
664 reveal_type(x) # N: Revealed type is "builtins.list[builtins.str]"
665 case _:
666 reveal_type(x) # N: Revealed type is "builtins.str"
667
668 def f1_rest(x: dict[str, str] | list[str] | str) -> None:
669 match x:
670 case {**rest}:
671 reveal_type(x) # N: Revealed type is "builtins.dict[builtins.str, builtins.str]"
672 case [*_]:
673 reveal_type(x) # N: Revealed type is "builtins.list[builtins.str]"
674 case _:
675 reveal_type(x) # N: Revealed type is "builtins.str"
676
677 def f2(x: Mapping[str, str] | Sequence[str] | str) -> None:
678 match x:
679 case {}:
680 reveal_type(x) # N: Revealed type is "typing.Mapping[builtins.str, builtins.str]"
681 case [*_]:
682 reveal_type(x) # N: Revealed type is "typing.Sequence[builtins.str]"
683 case _:
684 # TODO: this should be str
685 reveal_type(x) # E: Statement is unreachable
686
687 def f2_rest(x: Mapping[str, str] | Sequence[str] | str) -> None:
688 match x:
689 case {**rest}:
690 reveal_type(x) # N: Revealed type is "typing.Mapping[builtins.str, builtins.str]"
691 case [*_]:
692 reveal_type(x) # N: Revealed type is "typing.Sequence[builtins.str]"
693 case _:
694 # TODO: this should be str
695 reveal_type(x) # E: Statement is unreachable
696 [builtins fixtures/primitives.pyi]
697
698 [case testMatchMappingPatternNarrowingAny]
699 # flags: --strict-equality --warn-unreachable
700 from typing import Any
701
702 def f1(x: Any) -> None:
703 match x:
704 case {}:
705 reveal_type(x) # N: Revealed type is "Any"
706
707 def f2(x: Any) -> None:
708 match x:
709 case {"x": "y"}:
710 reveal_type(x) # N: Revealed type is "Any"
711 [builtins fixtures/dict.pyi]
712
713 -- Class Pattern --
714
715 [case testMatchClassPatternCapturePositional]
716 # flags: --strict-equality --warn-unreachable
717 from typing import Final
718
719 class A:
720 __match_args__: Final = ("a", "b")
721 a: str
722 b: int
723
724 m: A
725
726 match m:
727 case A(i, j):
728 reveal_type(i) # N: Revealed type is "builtins.str"
729 reveal_type(j) # N: Revealed type is "builtins.int"
730 [builtins fixtures/tuple.pyi]
731
732 [case testMatchClassPatternMemberClassCapturePositional]
733 # flags: --strict-equality --warn-unreachable
734 import b
735
736 m: b.A
737
738 match m:
739 case b.A(i, j):
740 reveal_type(i) # N: Revealed type is "builtins.str"
741 reveal_type(j) # N: Revealed type is "builtins.int"
742 [file b.py]
743 from typing import Final
744
745 class A:
746 __match_args__: Final = ("a", "b")
747 a: str
748 b: int
749 [builtins fixtures/tuple.pyi]
750
751 [case testMatchClassPatternCaptureKeyword]
752 # flags: --strict-equality --warn-unreachable
753 class A:
754 a: str
755 b: int
756
757 m: A
758
759 match m:
760 case A(a=i, b=j):
761 reveal_type(i) # N: Revealed type is "builtins.str"
762 reveal_type(j) # N: Revealed type is "builtins.int"
763
764 [case testMatchClassPatternCaptureSelf]
765 # flags: --strict-equality --warn-unreachable
766 m: object
767
768 match m:
769 case bool(a):
770 reveal_type(a) # N: Revealed type is "builtins.bool"
771 case bytearray(b):
772 reveal_type(b) # N: Revealed type is "builtins.bytearray"
773 case bytes(c):
774 reveal_type(c) # N: Revealed type is "builtins.bytes"
775 case dict(d):
776 reveal_type(d) # N: Revealed type is "builtins.dict[Any, Any]"
777 case float(e):
778 reveal_type(e) # N: Revealed type is "builtins.float"
779 case frozenset(f):
780 reveal_type(f) # N: Revealed type is "builtins.frozenset[Any]"
781 case int(g):
782 reveal_type(g) # N: Revealed type is "builtins.int"
783 case list(h):
784 reveal_type(h) # N: Revealed type is "builtins.list[Any]"
785 case set(i):
786 reveal_type(i) # N: Revealed type is "builtins.set[Any]"
787 case str(j):
788 reveal_type(j) # N: Revealed type is "builtins.str"
789 case tuple(k):
790 reveal_type(k) # N: Revealed type is "builtins.tuple[Any, ...]"
791 [builtins fixtures/primitives.pyi]
792
793 [case testMatchClassPatternNarrowSelfCapture]
794 # flags: --strict-equality --warn-unreachable
795 m: object
796
797 match m:
798 case bool():
799 reveal_type(m) # N: Revealed type is "builtins.bool"
800 case bytearray():
801 reveal_type(m) # N: Revealed type is "builtins.bytearray"
802 case bytes():
803 reveal_type(m) # N: Revealed type is "builtins.bytes"
804 case dict():
805 reveal_type(m) # N: Revealed type is "builtins.dict[Any, Any]"
806 case float():
807 reveal_type(m) # N: Revealed type is "builtins.float"
808 case frozenset():
809 reveal_type(m) # N: Revealed type is "builtins.frozenset[Any]"
810 case int():
811 reveal_type(m) # N: Revealed type is "builtins.int"
812 case list():
813 reveal_type(m) # N: Revealed type is "builtins.list[Any]"
814 case set():
815 reveal_type(m) # N: Revealed type is "builtins.set[Any]"
816 case str():
817 reveal_type(m) # N: Revealed type is "builtins.str"
818 case tuple():
819 reveal_type(m) # N: Revealed type is "builtins.tuple[Any, ...]"
820 [builtins fixtures/primitives.pyi]
821
822 [case testMatchClassPatternCaptureSelfSubtype]
823 # flags: --strict-equality --warn-unreachable
824 class A(str):
825 pass
826
827 class B(str):
828 __match_args__ = ("b",)
829 b: int
830
831 def f1(x: A):
832 match x:
833 case A(a):
834 reveal_type(a) # N: Revealed type is "__main__.A"
835
836 def f2(x: B):
837 match x:
838 case B(b):
839 reveal_type(b) # N: Revealed type is "builtins.int"
840 [builtins fixtures/tuple.pyi]
841
842 [case testMatchInvalidClassPattern]
843 # flags: --strict-equality --warn-unreachable
844 m: object
845
846 match m:
847 case xyz(y): # E: Name "xyz" is not defined
848 reveal_type(m) # N: Revealed type is "Any"
849 reveal_type(y) # N: Revealed type is "Any"
850
851 match m:
852 case xyz(z=x): # E: Name "xyz" is not defined
853 reveal_type(x) # N: Revealed type is "Any"
854 case (xyz1() as n) | (xyz2(attr=n)): # E: Name "xyz1" is not defined \
855 # E: Name "xyz2" is not defined
856 reveal_type(n) # N: Revealed type is "Any"
857
858 [case testMatchClassPatternCaptureDataclass]
859 # flags: --strict-equality --warn-unreachable
860 from dataclasses import dataclass
861
862 @dataclass
863 class A:
864 a: str
865 b: int
866
867 m: A
868
869 match m:
870 case A(i, j):
871 reveal_type(i) # N: Revealed type is "builtins.str"
872 reveal_type(j) # N: Revealed type is "builtins.int"
873 [builtins fixtures/dataclasses.pyi]
874
875 [case testMatchClassPatternCaptureDataclassNoMatchArgs]
876 # flags: --strict-equality --warn-unreachable
877 from dataclasses import dataclass
878
879 @dataclass(match_args=False)
880 class A:
881 a: str
882 b: int
883
884 m: A
885
886 match m:
887 case A(i, j): # E: Class "__main__.A" doesn't define "__match_args__"
888 pass # E: Statement is unreachable
889 [builtins fixtures/dataclasses.pyi]
890
891 [case testMatchClassPatternCaptureDataclassPartialMatchArgs]
892 # flags: --strict-equality --warn-unreachable
893 from dataclasses import dataclass, field
894
895 @dataclass
896 class A:
897 a: str
898 b: int = field(init=False)
899
900 m: A
901
902 match m:
903 case A(i, j): # E: Too many positional patterns for class pattern
904 pass # E: Statement is unreachable
905 case A(k):
906 reveal_type(k) # N: Revealed type is "builtins.str"
907 [builtins fixtures/dataclasses.pyi]
908
909 [case testMatchClassPatternCaptureNamedTupleInline]
910 # flags: --strict-equality --warn-unreachable
911 from collections import namedtuple
912
913 A = namedtuple("A", ["a", "b"])
914
915 m: A
916
917 match m:
918 case A(i, j):
919 reveal_type(i) # N: Revealed type is "Any"
920 reveal_type(j) # N: Revealed type is "Any"
921 [builtins fixtures/list.pyi]
922
923 [case testMatchClassPatternCaptureNamedTupleInlineTyped]
924 # flags: --strict-equality --warn-unreachable
925 from typing import NamedTuple
926
927 A = NamedTuple("A", [("a", str), ("b", int)])
928
929 m: A
930
931 match m:
932 case A(i, j):
933 reveal_type(i) # N: Revealed type is "builtins.str"
934 reveal_type(j) # N: Revealed type is "builtins.int"
935 [builtins fixtures/list.pyi]
936
937 [case testMatchClassPatternCaptureNamedTupleClass]
938 # flags: --strict-equality --warn-unreachable
939 from typing import NamedTuple
940
941 class A(NamedTuple):
942 a: str
943 b: int
944
945 m: A
946
947 match m:
948 case A(i, j):
949 reveal_type(i) # N: Revealed type is "builtins.str"
950 reveal_type(j) # N: Revealed type is "builtins.int"
951 [builtins fixtures/tuple.pyi]
952
953 [case testMatchSequencePatternCaptureNamedTuple]
954 # flags: --strict-equality --warn-unreachable
955 from typing import NamedTuple
956
957 class N(NamedTuple):
958 x: int
959 y: str
960
961 a = N(1, "a")
962
963 match a:
964 case [x, y]:
965 reveal_type(x) # N: Revealed type is "builtins.int"
966 reveal_type(y) # N: Revealed type is "builtins.str"
967 [builtins fixtures/tuple.pyi]
968
969 [case testMatchClassPatternCaptureGeneric]
970 # flags: --strict-equality --warn-unreachable
971 from typing import Generic, TypeVar
972
973 T = TypeVar('T')
974
975 class A(Generic[T]):
976 a: T
977
978 m: object
979
980 match m:
981 case A(a=i):
982 reveal_type(m) # N: Revealed type is "__main__.A[Any]"
983 reveal_type(i) # N: Revealed type is "Any"
984
985 [case testMatchClassPatternCaptureVariadicGeneric]
986 # flags: --strict-equality --warn-unreachable
987 from typing import Generic, Tuple
988 from typing_extensions import TypeVarTuple, Unpack
989
990 Ts = TypeVarTuple('Ts')
991 class A(Generic[Unpack[Ts]]):
992 a: Tuple[Unpack[Ts]]
993
994 m: object
995 match m:
996 case A(a=i):
997 reveal_type(m) # N: Revealed type is "__main__.A[Unpack[builtins.tuple[Any, ...]]]"
998 reveal_type(i) # N: Revealed type is "builtins.tuple[Any, ...]"
999 [builtins fixtures/tuple.pyi]
1000
1001 [case testMatchClassPatternCaptureGenericAlreadyKnown]
1002 # flags: --strict-equality --warn-unreachable
1003 from typing import Generic, TypeVar
1004
1005 T = TypeVar('T')
1006
1007 class A(Generic[T]):
1008 a: T
1009
1010 m: A[int]
1011
1012 match m:
1013 case A(a=i):
1014 reveal_type(m) # N: Revealed type is "__main__.A[builtins.int]"
1015 reveal_type(i) # N: Revealed type is "builtins.int"
1016
1017 [case testMatchClassPatternCaptureFilledGenericTypeAlias]
1018 # flags: --strict-equality --warn-unreachable
1019 from typing import Generic, TypeVar
1020
1021 T = TypeVar('T')
1022
1023 class A(Generic[T]):
1024 a: T
1025
1026 B = A[int]
1027
1028 m: object
1029
1030 match m:
1031 case B(a=i): # E: Class pattern class must not be a type alias with type parameters
1032 reveal_type(i) # E: Statement is unreachable
1033
1034 [case testMatchClassPatternCaptureGenericTypeAlias]
1035 # flags: --strict-equality --warn-unreachable
1036 from typing import Generic, TypeVar
1037
1038 T = TypeVar('T')
1039
1040 class A(Generic[T]):
1041 a: T
1042
1043 B = A
1044
1045 m: object
1046
1047 match m:
1048 case B(a=i):
1049 pass
1050
1051 [case testMatchClassPatternNarrows]
1052 # flags: --strict-equality --warn-unreachable
1053 from typing import Final
1054
1055 class A:
1056 __match_args__: Final = ("a", "b")
1057 a: str
1058 b: int
1059
1060 m: object
1061
1062 match m:
1063 case A():
1064 reveal_type(m) # N: Revealed type is "__main__.A"
1065 case A(i, j):
1066 reveal_type(m) # N: Revealed type is "__main__.A"
1067 [builtins fixtures/tuple.pyi]
1068
1069 [case testMatchClassPatternNarrowsUnion]
1070 # flags: --strict-equality --warn-unreachable
1071 from typing import Final, Union
1072
1073 class A:
1074 __match_args__: Final = ("a", "b")
1075 a: str
1076 b: int
1077
1078 class B:
1079 __match_args__: Final = ("a", "b")
1080 a: int
1081 b: str
1082
1083 m: Union[A, B]
1084
1085 match m:
1086 case A():
1087 reveal_type(m) # N: Revealed type is "__main__.A"
1088
1089 match m:
1090 case A(i, j):
1091 reveal_type(m) # N: Revealed type is "__main__.A"
1092 reveal_type(i) # N: Revealed type is "builtins.str"
1093 reveal_type(j) # N: Revealed type is "builtins.int"
1094
1095 match m:
1096 case B():
1097 reveal_type(m) # N: Revealed type is "__main__.B"
1098
1099 match m:
1100 case B(k, l):
1101 reveal_type(m) # N: Revealed type is "__main__.B"
1102 reveal_type(k) # N: Revealed type is "builtins.int"
1103 reveal_type(l) # N: Revealed type is "builtins.str"
1104 [builtins fixtures/tuple.pyi]
1105
1106 [case testMatchClassPatternAlreadyNarrower]
1107 # flags: --strict-equality --warn-unreachable
1108 from typing import Final
1109
1110 class A:
1111 __match_args__: Final = ("a", "b")
1112 a: str
1113 b: int
1114 class B(A): ...
1115
1116 m: B
1117
1118 match m:
1119 case A():
1120 reveal_type(m) # N: Revealed type is "__main__.B"
1121
1122 match m:
1123 case A(i, j):
1124 reveal_type(m) # N: Revealed type is "__main__.B"
1125 [builtins fixtures/tuple.pyi]
1126
1127 [case testMatchClassPatternIntersection]
1128 # flags: --strict-equality --warn-unreachable
1129 from typing import Final
1130
1131 class A:
1132 __match_args__: Final = ("a", "b")
1133 a: str
1134 b: int
1135 class B: ...
1136
1137 m: B
1138
1139 match m:
1140 case A():
1141 reveal_type(m) # N: Revealed type is "__main__.<subclass of "__main__.B" and "__main__.A">"
1142 case A(i, j):
1143 reveal_type(m) # N: Revealed type is "__main__.<subclass of "__main__.B" and "__main__.A">"
1144 [builtins fixtures/tuple.pyi]
1145
1146 [case testMatchClassPatternNonexistentKeyword]
1147 # flags: --strict-equality --warn-unreachable
1148 from typing import Any
1149 class A: ...
1150
1151 m: object
1152 n: Any
1153
1154 match m:
1155 case A(a=j): # E: Class "__main__.A" has no attribute "a"
1156 reveal_type(m) # N: Revealed type is "__main__.A"
1157 reveal_type(j) # N: Revealed type is "Any"
1158
1159 match n:
1160 # Matching against object should not emit an error for non-existing keys
1161 case object(a=k):
1162 reveal_type(n) # N: Revealed type is "builtins.object"
1163 reveal_type(n.a) # N: Revealed type is "Any"
1164 reveal_type(k) # N: Revealed type is "Any"
1165
1166 [case testMatchClassPatternDuplicateKeyword]
1167 # flags: --strict-equality --warn-unreachable
1168 class A:
1169 a: str
1170
1171 m: object
1172
1173 match m:
1174 case A(a=i, a=j): # E: Duplicate keyword pattern "a"
1175 pass # E: Statement is unreachable
1176
1177 [case testMatchClassPatternDuplicateImplicitKeyword]
1178 # flags: --strict-equality --warn-unreachable
1179 from typing import Final
1180
1181 class A:
1182 __match_args__: Final = ("a",)
1183 a: str
1184
1185 m: object
1186
1187 match m:
1188 case A(i, a=j): # E: Keyword "a" already matches a positional pattern
1189 pass # E: Statement is unreachable
1190 [builtins fixtures/tuple.pyi]
1191
1192 [case testMatchClassPatternTooManyPositionals]
1193 # flags: --strict-equality --warn-unreachable
1194 from typing import Final
1195
1196 class A:
1197 __match_args__: Final = ("a", "b")
1198 a: str
1199 b: int
1200
1201 m: object
1202
1203 match m:
1204 case A(i, j, k): # E: Too many positional patterns for class pattern
1205 pass # E: Statement is unreachable
1206 [builtins fixtures/tuple.pyi]
1207
1208 [case testMatchClassPatternIsNotType]
1209 # flags: --strict-equality --warn-unreachable
1210 from typing import Any
1211
1212 def match_int(m: object, a: int):
1213 match m:
1214 case a(i, j): # E: Expected type in class pattern; found "builtins.int"
1215 reveal_type(i) # E: Statement is unreachable
1216 reveal_type(j)
1217
1218 def match_int_str(m: object, a: int | str):
1219 match m:
1220 case a(i, j): # E: Expected type in class pattern; found "builtins.int" \
1221 # E: Expected type in class pattern; found "builtins.str"
1222 reveal_type(i) # E: Statement is unreachable
1223 reveal_type(j)
1224
1225 def match_int_any(m: object, a: int | Any):
1226 match m:
1227 case a(i, j): # E: Expected type in class pattern; found "builtins.int"
1228 reveal_type(i) # N: Revealed type is "Any"
1229 reveal_type(j) # N: Revealed type is "Any"
1230
1231 [case testMatchClassPatternAny]
1232 # flags: --strict-equality --warn-unreachable
1233 from typing import Any
1234
1235 Foo: Any
1236 m: object
1237
1238 match m:
1239 case Foo():
1240 pass
1241
1242 [case testMatchClassPatternCallable]
1243 # flags: --strict-equality --warn-unreachable
1244 from typing import Callable, Any
1245
1246 class FnImpl:
1247 def __call__(self, x: object, /) -> int: ...
1248
1249 def test_any(x: Any) -> None:
1250 match x:
1251 case Callable() as fn:
1252 reveal_type(fn) # N: Revealed type is "def (*Any, **Any) -> Any"
1253 case other:
1254 reveal_type(other) # N: Revealed type is "Any"
1255
1256 def test_object(x: object) -> None:
1257 match x:
1258 case Callable() as fn:
1259 reveal_type(fn) # N: Revealed type is "def (*Any, **Any) -> Any"
1260 case other:
1261 reveal_type(other) # N: Revealed type is "builtins.object"
1262
1263 def test_impl(x: FnImpl) -> None:
1264 match x:
1265 case Callable() as fn:
1266 reveal_type(fn) # N: Revealed type is "__main__.FnImpl"
1267 case other:
1268 reveal_type(other) # E: Statement is unreachable
1269
1270 def test_callable(x: Callable[[object], int]) -> None:
1271 match x:
1272 case Callable() as fn:
1273 reveal_type(fn) # N: Revealed type is "def (builtins.object) -> builtins.int"
1274 case other:
1275 reveal_type(other) # E: Statement is unreachable
1276
1277 [case testMatchClassPatternCallbackProtocol]
1278 # flags: --strict-equality --warn-unreachable
1279 from typing import Any, Callable
1280 from typing_extensions import Protocol, runtime_checkable
1281
1282 @runtime_checkable
1283 class FnProto(Protocol):
1284 def __call__(self, x: int, /) -> object: ...
1285
1286 class FnImpl:
1287 def __call__(self, x: object, /) -> int: ...
1288
1289 def test_any(x: Any) -> None:
1290 match x:
1291 case FnProto() as fn:
1292 reveal_type(fn) # N: Revealed type is "__main__.FnProto"
1293 case other:
1294 reveal_type(other) # N: Revealed type is "Any"
1295
1296 def test_object(x: object) -> None:
1297 match x:
1298 case FnProto() as fn:
1299 reveal_type(fn) # N: Revealed type is "__main__.FnProto"
1300 case other:
1301 reveal_type(other) # N: Revealed type is "builtins.object"
1302
1303 def test_impl(x: FnImpl) -> None:
1304 match x:
1305 case FnProto() as fn:
1306 reveal_type(fn) # N: Revealed type is "__main__.FnImpl"
1307 case other:
1308 reveal_type(other) # E: Statement is unreachable
1309
1310 def test_callable(x: Callable[[object], int]) -> None:
1311 match x:
1312 case FnProto() as fn:
1313 reveal_type(fn) # N: Revealed type is "def (builtins.object) -> builtins.int"
1314 case other:
1315 reveal_type(other) # E: Statement is unreachable
1316
1317 [builtins fixtures/dict.pyi]
1318
1319 [case testMatchClassPatternAnyCallableProtocol]
1320 # flags: --strict-equality --warn-unreachable
1321 from typing import Any, Callable
1322 from typing_extensions import Protocol, runtime_checkable
1323
1324 @runtime_checkable
1325 class AnyCallable(Protocol):
1326 def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
1327
1328 class FnImpl:
1329 def __call__(self, x: object, /) -> int: ...
1330
1331 def test_object(x: object) -> None:
1332 match x:
1333 case AnyCallable() as fn:
1334 reveal_type(fn) # N: Revealed type is "__main__.AnyCallable"
1335 case other:
1336 reveal_type(other) # N: Revealed type is "builtins.object"
1337
1338 def test_impl(x: FnImpl) -> None:
1339 match x:
1340 case AnyCallable() as fn:
1341 reveal_type(fn) # N: Revealed type is "__main__.FnImpl"
1342 case other:
1343 reveal_type(other) # E: Statement is unreachable
1344
1345 def test_callable(x: Callable[[object], int]) -> None:
1346 match x:
1347 case AnyCallable() as fn:
1348 reveal_type(fn) # N: Revealed type is "def (builtins.object) -> builtins.int"
1349 case other:
1350 reveal_type(other) # E: Statement is unreachable
1351
1352 [builtins fixtures/dict.pyi]
1353
1354
1355 [case testMatchClassPatternProtocol]
1356 # flags: --strict-equality --warn-unreachable
1357 from typing import Any
1358 from typing_extensions import Protocol, runtime_checkable
1359
1360 @runtime_checkable
1361 class Proto(Protocol):
1362 def foo(self, x: int, /) -> object: ...
1363
1364 class Impl:
1365 def foo(self, x: object, /) -> int: ...
1366
1367 def test_object(x: object) -> None:
1368 match x:
1369 case Proto() as y:
1370 reveal_type(y) # N: Revealed type is "__main__.Proto"
1371
1372 def test_impl(x: Impl) -> None:
1373 match x:
1374 case Proto() as y:
1375 reveal_type(y) # N: Revealed type is "__main__.Impl"
1376
1377 [builtins fixtures/dict.pyi]
1378
1379
1380 [case testMatchClassPatternNestedGenerics]
1381 # flags: --strict-equality --warn-unreachable
1382 # From cpython test_patma.py
1383 x = [[{0: 0}]]
1384 match x:
1385 case list([({-0-0j: int(real=0+0j, imag=0-0j) | (1) as z},)]):
1386 y = 0
1387
1388 reveal_type(x) # N: Revealed type is "builtins.list[builtins.list[builtins.dict[builtins.int, builtins.int]]]"
1389 reveal_type(y) # N: Revealed type is "builtins.int"
1390 reveal_type(z) # N: Revealed type is "builtins.int"
1391 [builtins fixtures/dict-full.pyi]
1392
1393 [case testMatchClassPatternTypeObject]
1394 # flags: --strict-equality --warn-unreachable
1395 class Example:
1396 __match_args__ = ("value",)
1397 def __init__(self, value: str) -> None:
1398 self.value = value
1399
1400 def f1(subclass: type[Example]) -> None:
1401 match subclass("a"):
1402 case Example(value):
1403 reveal_type(value) # N: Revealed type is "builtins.str"
1404 case anything:
1405 reveal_type(anything) # E: Statement is unreachable
1406
1407 def f2(subclass: type[Example]) -> None:
1408 match Example("a"):
1409 case subclass(value):
1410 reveal_type(value) # N: Revealed type is "builtins.str"
1411 case anything:
1412 reveal_type(anything) # N: Revealed type is "__main__.Example"
1413
1414 def f3(subclass: type[Example]) -> None:
1415 match subclass("a"):
1416 case subclass(value):
1417 reveal_type(value) # N: Revealed type is "builtins.str"
1418 case anything:
1419 reveal_type(anything) # N: Revealed type is "__main__.Example"
1420
1421 class Example2:
1422 __match_args__ = ("value",)
1423 def __init__(self, value: str) -> None:
1424 self.value = value
1425
1426 def f4(T: type[Example | Example2]) -> None:
1427 match T("a"):
1428 case Example(value):
1429 reveal_type(value) # N: Revealed type is "builtins.str"
1430 case anything:
1431 reveal_type(anything) # N: Revealed type is "__main__.Example2"
1432
1433 def f5(T: type[Example | Example2]) -> None:
1434 match Example("a"):
1435 case T(value):
1436 reveal_type(value) # N: Revealed type is "builtins.str"
1437 case anything:
1438 reveal_type(anything) # N: Revealed type is "__main__.Example"
1439
1440 def f6(T: type[Example | Example2]) -> None:
1441 match T("a"):
1442 case T(value):
1443 reveal_type(value) # N: Revealed type is "builtins.str"
1444 case anything:
1445 reveal_type(anything) # N: Revealed type is "__main__.Example | __main__.Example2"
1446
1447 def f7(m: object, t: type[object]) -> None:
1448 match m:
1449 case t():
1450 reveal_type(m) # N: Revealed type is "builtins.object"
1451 case _:
1452 reveal_type(m) # N: Revealed type is "builtins.object"
1453 [builtins fixtures/tuple.pyi]
1454
1455 [case testMatchClassPatternTypeObjectGeneric]
1456 # flags: --strict-equality --warn-unreachable
1457 from typing import TypeVar
1458 T = TypeVar("T")
1459
1460 def print_test(m: object, typ: type[T]) -> T:
1461 match m:
1462 case typ():
1463 reveal_type(m) # N: Revealed type is "T`-1"
1464 return m
1465 case str():
1466 reveal_type(m) # N: Revealed type is "builtins.str"
1467 case _:
1468 reveal_type(m) # N: Revealed type is "builtins.object"
1469 raise
1470
1471 [case testMatchClassPatternTupleAlias]
1472 # flags: --strict-equality --warn-unreachable
1473 from typing import Tuple
1474
1475 tuple_alias = tuple
1476 Tuple_alias = Tuple
1477
1478 def main(m: object):
1479 match m:
1480 case tuple():
1481 reveal_type(m) # N: Revealed type is "builtins.tuple[Any, ...]"
1482 case _:
1483 reveal_type(m) # N: Revealed type is "builtins.object"
1484
1485 match m:
1486 case tuple_alias():
1487 reveal_type(m) # N: Revealed type is "builtins.tuple[Any, ...]"
1488 case _:
1489 reveal_type(m) # N: Revealed type is "builtins.object"
1490
1491 match m:
1492 # With real typeshed you'll get an error like this instead:
1493 # Expected type in class pattern; found "typing._SpecialForm"
1494 case Tuple(): # E: Expected type in class pattern; found "builtins.int"
1495 reveal_type(m) # E: Statement is unreachable
1496 case _:
1497 reveal_type(m) # N: Revealed type is "builtins.object"
1498
1499 match m:
1500 # This is a false negative, it will raise at runtime
1501 case Tuple_alias():
1502 reveal_type(m) # N: Revealed type is "builtins.tuple[Any, ...]"
1503 case _:
1504 reveal_type(m) # N: Revealed type is "builtins.object"
1505 [builtins fixtures/tuple.pyi]
1506
1507 [case testMatchNonFinalMatchArgs]
1508 # flags: --strict-equality --warn-unreachable
1509 class A:
1510 __match_args__ = ("a", "b")
1511 a: str
1512 b: int
1513
1514 m: object
1515
1516 match m:
1517 case A(i, j):
1518 reveal_type(i) # N: Revealed type is "builtins.str"
1519 reveal_type(j) # N: Revealed type is "builtins.int"
1520 [builtins fixtures/tuple.pyi]
1521
1522 [case testMatchAnyTupleMatchArgs]
1523 # flags: --strict-equality --warn-unreachable
1524 from typing import Tuple, Any
1525
1526 class A:
1527 __match_args__: Tuple[Any, ...]
1528 a: str
1529 b: int
1530
1531 m: object
1532
1533 match m:
1534 case A(i, j, k):
1535 reveal_type(i) # N: Revealed type is "Any"
1536 reveal_type(j) # N: Revealed type is "Any"
1537 reveal_type(k) # N: Revealed type is "Any"
1538 [builtins fixtures/tuple.pyi]
1539
1540 [case testMatchNonLiteralMatchArgs]
1541 # flags: --strict-equality --warn-unreachable
1542 from typing import Final
1543
1544 b: str = "b"
1545 class A:
1546 __match_args__: Final = ("a", b) # N: __match_args__ must be a tuple containing string literals for checking of match statements to work
1547 a: str
1548 b: int
1549
1550 m: object
1551
1552 match m:
1553 case A(i, j, k): # E: Too many positional patterns for class pattern
1554 pass # E: Statement is unreachable
1555 case A(i, j):
1556 reveal_type(i) # N: Revealed type is "builtins.str"
1557 reveal_type(j) # N: Revealed type is "Any"
1558 [builtins fixtures/tuple.pyi]
1559
1560 [case testMatchExternalMatchArgs]
1561 # flags: --strict-equality --warn-unreachable
1562 from typing import Final, Literal
1563
1564 args: Final = ("a", "b")
1565 class A:
1566 __match_args__: Final = args
1567 a: str
1568 b: int
1569
1570 arg: Final = "a"
1571 arg2: Literal["b"] = "b"
1572 class B:
1573 __match_args__: Final = (arg, arg2)
1574 a: str
1575 b: int
1576
1577 [builtins fixtures/tuple.pyi]
1578 [typing fixtures/typing-medium.pyi]
1579
1580 -- As Pattern --
1581
1582 [case testMatchAsPattern]
1583 # flags: --strict-equality --warn-unreachable
1584 m: int
1585
1586 match m:
1587 case x as l:
1588 reveal_type(x) # N: Revealed type is "builtins.int"
1589 reveal_type(l) # N: Revealed type is "builtins.int"
1590
1591 [case testMatchAsPatternNarrows]
1592 # flags: --strict-equality --warn-unreachable
1593 m: object
1594
1595 match m:
1596 case int() as l:
1597 reveal_type(l) # N: Revealed type is "builtins.int"
1598
1599 [case testMatchAsPatternCapturesOr]
1600 # flags: --strict-equality --warn-unreachable
1601 m: object
1602
1603 match m:
1604 case 1 | 2 as n:
1605 reveal_type(n) # N: Revealed type is "Literal[1] | Literal[2]"
1606
1607 [case testMatchAsPatternAlreadyNarrower]
1608 # flags: --strict-equality --warn-unreachable
1609 m: bool
1610
1611 match m:
1612 case int() as l:
1613 reveal_type(l) # N: Revealed type is "builtins.bool"
1614
1615 -- Or Pattern --
1616
1617 [case testMatchOrPatternNarrows]
1618 # flags: --strict-equality --warn-unreachable
1619 m: object
1620
1621 match m:
1622 case 1 | 2:
1623 reveal_type(m) # N: Revealed type is "Literal[1] | Literal[2]"
1624
1625 [case testMatchOrPatternNarrowsStr]
1626 # flags: --strict-equality --warn-unreachable
1627 m: object
1628
1629 match m:
1630 case "foo" | "bar":
1631 reveal_type(m) # N: Revealed type is "Literal['foo'] | Literal['bar']"
1632
1633 [case testMatchOrPatternNarrowsUnion]
1634 # flags: --strict-equality --warn-unreachable
1635 m: object
1636
1637 match m:
1638 case 1 | "foo":
1639 reveal_type(m) # N: Revealed type is "Literal[1] | Literal['foo']"
1640
1641 [case testMatchOrPatternCapturesMissing]
1642 # flags: --strict-equality --warn-unreachable
1643 from typing import List
1644 m: List[int]
1645
1646 match m:
1647 case [x, y] | list(x): # E: Alternative patterns bind different names
1648 reveal_type(x) # N: Revealed type is "builtins.int | builtins.list[builtins.int]"
1649 reveal_type(y) # N: Revealed type is "builtins.int"
1650 [builtins fixtures/list.pyi]
1651
1652 [case testMatchOrPatternCapturesJoin]
1653 # flags: --strict-equality --warn-unreachable
1654 m: object
1655
1656 match m:
1657 case list(x) | dict(x):
1658 reveal_type(x) # N: Revealed type is "builtins.list[Any] | builtins.dict[Any, Any]"
1659 [builtins fixtures/dict.pyi]
1660
1661 -- Interactions --
1662
1663 [case testMatchCapturePatternMultipleCases]
1664 # flags: --strict-equality --warn-unreachable
1665 m: object
1666
1667 match m:
1668 case int(x):
1669 reveal_type(x) # N: Revealed type is "builtins.int"
1670 case str(x):
1671 reveal_type(x) # N: Revealed type is "builtins.str"
1672
1673 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str"
1674
1675 [case testMatchCapturePatternMultipleCaptures]
1676 # flags: --strict-equality --warn-unreachable
1677 from typing import Iterable
1678
1679 m: Iterable[int]
1680
1681 match m:
1682 case [x, x]: # E: Multiple assignments to name "x" in pattern
1683 reveal_type(x) # N: Revealed type is "builtins.int"
1684 [builtins fixtures/list.pyi]
1685
1686 [case testMatchCapturePatternPreexistingSame]
1687 # flags: --strict-equality --warn-unreachable
1688 a: int
1689 m: int
1690
1691 match m:
1692 case a:
1693 reveal_type(a) # N: Revealed type is "builtins.int"
1694
1695 [case testMatchCapturePatternPreexistingNarrows]
1696 # flags: --strict-equality --warn-unreachable
1697 a: int
1698 m: bool
1699
1700 match m:
1701 case a:
1702 reveal_type(a) # N: Revealed type is "builtins.bool"
1703
1704 reveal_type(a) # N: Revealed type is "builtins.bool"
1705 a = 3
1706 reveal_type(a) # N: Revealed type is "builtins.int"
1707
1708 [case testMatchCapturePatternAfterPreviousCase]
1709 # flags: --strict-equality --warn-unreachable
1710
1711 def f1(x: int | None, y: int):
1712 match x:
1713 case None:
1714 pass
1715 case y:
1716 reveal_type(y) # N: Revealed type is "builtins.int"
1717
1718 def f2(x: int | None, y: int, cond: bool):
1719 match x:
1720 case None if cond:
1721 pass
1722 case y: # E: Incompatible types in capture pattern (pattern captures type "int | None", variable has type "int")
1723 reveal_type(y) # N: Revealed type is "builtins.int"
1724
1725 def f3(x: int | None, y: int):
1726 match x:
1727 case None if True:
1728 pass
1729 case y:
1730 reveal_type(y) # N: Revealed type is "builtins.int"
1731
1732 match x:
1733 case None if False:
1734 pass # E: Statement is unreachable
1735 case y: # E: Incompatible types in capture pattern (pattern captures type "int | None", variable has type "int")
1736 reveal_type(y) # N: Revealed type is "builtins.int"
1737
1738 [case testMatchCapturePatternPreexistingIncompatible]
1739 # flags: --strict-equality --warn-unreachable
1740 a: str
1741 m: int
1742
1743 match m:
1744 case a: # E: Incompatible types in capture pattern (pattern captures type "int", variable has type "str")
1745 reveal_type(a) # N: Revealed type is "builtins.str"
1746
1747 reveal_type(a) # N: Revealed type is "builtins.str"
1748
1749 [case testMatchCapturePatternPreexistingIncompatibleLater]
1750 # flags: --strict-equality --warn-unreachable
1751 a: str
1752 m: object
1753
1754 match m:
1755 case str(a):
1756 reveal_type(a) # N: Revealed type is "builtins.str"
1757 case int(a): # E: Incompatible types in capture pattern (pattern captures type "int", variable has type "str")
1758 reveal_type(a) # N: Revealed type is "builtins.str"
1759
1760 reveal_type(a) # N: Revealed type is "builtins.str"
1761
1762 [case testMatchCapturePatternFromFunctionReturningUnion]
1763 # flags: --strict-equality --warn-unreachable
1764 def func1(arg: bool) -> str | int: ...
1765 def func2(arg: bool) -> bytes | int: ...
1766
1767 def main() -> None:
1768 match func1(True):
1769 case str(a):
1770 match func2(True):
1771 case c:
1772 reveal_type(a) # N: Revealed type is "builtins.str"
1773 reveal_type(c) # N: Revealed type is "builtins.bytes | builtins.int"
1774 reveal_type(a) # N: Revealed type is "builtins.str"
1775 case a:
1776 reveal_type(a) # N: Revealed type is "builtins.int"
1777
1778 [case testMatchCapturePatternFromAsyncFunctionReturningUnion]
1779 # flags: --strict-equality --warn-unreachable
1780 async def func1(arg: bool) -> str | int: ...
1781 async def func2(arg: bool) -> bytes | int: ...
1782
1783 async def main() -> None:
1784 match await func1(True):
1785 case str(a):
1786 match await func2(True):
1787 case c:
1788 reveal_type(a) # N: Revealed type is "builtins.str"
1789 reveal_type(c) # N: Revealed type is "builtins.bytes | builtins.int"
1790 reveal_type(a) # N: Revealed type is "builtins.str"
1791 case a:
1792 reveal_type(a) # N: Revealed type is "builtins.int"
1793
1794 -- Guards --
1795
1796 [case testMatchSimplePatternGuard]
1797 # flags: --strict-equality --warn-unreachable
1798 m: str
1799
1800 def guard() -> bool: ...
1801
1802 match m:
1803 case a if guard():
1804 reveal_type(a) # N: Revealed type is "builtins.str"
1805
1806 [case testMatchAlwaysTruePatternGuard]
1807 # flags: --strict-equality --warn-unreachable
1808 m: str
1809
1810 match m:
1811 case a if True:
1812 reveal_type(a) # N: Revealed type is "builtins.str"
1813
1814 [case testMatchAlwaysFalsePatternGuard]
1815 # flags: --strict-equality --warn-unreachable
1816 m: str
1817
1818 match m:
1819 case a if False:
1820 reveal_type(a) # E: Statement is unreachable
1821
1822 [case testMatchRedefiningPatternGuard]
1823 # flags: --strict-equality --warn-unreachable
1824 m: str
1825
1826 match m:
1827 case a if a := 1: # E: Incompatible types in assignment (expression has type "int", variable has type "str")
1828 reveal_type(a) # N: Revealed type is "Literal[1]?"
1829
1830 [case testMatchAssigningPatternGuard]
1831 # flags: --strict-equality --warn-unreachable
1832 m: str
1833
1834 match m:
1835 case a if a := "test":
1836 reveal_type(a) # N: Revealed type is "builtins.str"
1837
1838 [case testMatchNarrowingPatternGuard]
1839 # flags: --strict-equality --warn-unreachable
1840 m: object
1841
1842 match m:
1843 case a if isinstance(a, str):
1844 reveal_type(a) # N: Revealed type is "builtins.str"
1845 [builtins fixtures/isinstancelist.pyi]
1846
1847 [case testMatchIncompatiblePatternGuard]
1848 # flags: --strict-equality --warn-unreachable
1849 class A: ...
1850 class B: ...
1851
1852 m: A
1853
1854 match m:
1855 case a if isinstance(a, B):
1856 reveal_type(a) # N: Revealed type is "__main__.<subclass of "__main__.A" and "__main__.B">"
1857 [builtins fixtures/isinstancelist.pyi]
1858
1859 [case testMatchUnreachablePatternGuard]
1860 # flags: --strict-equality --warn-unreachable
1861 m: str
1862
1863 match m:
1864 case a if isinstance(a, int): # E: Subclass of "str" and "int" cannot exist: would have incompatible method signatures
1865 reveal_type(a) # E: Statement is unreachable
1866 [builtins fixtures/isinstancelist.pyi]
1867
1868 [case testMatchSubjectAssignExprWithGuard]
1869 # flags: --strict-equality --warn-unreachable
1870 from typing import Optional
1871 def func() -> Optional[str]: ...
1872
1873 match m := func():
1874 case _ if not m:
1875 reveal_type(m) # N: Revealed type is "Literal[''] | None"
1876 case _:
1877 reveal_type(m) # N: Revealed type is "builtins.str"
1878
1879 -- Exhaustiveness --
1880
1881 [case testMatchUnionNegativeNarrowing]
1882 # flags: --strict-equality --warn-unreachable
1883 from typing import Union
1884
1885 m: Union[str, int]
1886
1887 match m:
1888 case str(a):
1889 reveal_type(a) # N: Revealed type is "builtins.str"
1890 reveal_type(m) # N: Revealed type is "builtins.str"
1891 case b:
1892 reveal_type(b) # N: Revealed type is "builtins.int"
1893 reveal_type(m) # N: Revealed type is "builtins.int"
1894
1895 [case testMatchOrPatternNegativeNarrowing]
1896 # flags: --strict-equality --warn-unreachable
1897 from typing import Union
1898
1899 m: Union[str, bytes, int]
1900
1901 match m:
1902 case str(a) | bytes(a):
1903 reveal_type(a) # N: Revealed type is "builtins.str | builtins.bytes"
1904 reveal_type(m) # N: Revealed type is "builtins.str | builtins.bytes"
1905 case b:
1906 reveal_type(b) # N: Revealed type is "builtins.int"
1907
1908 [case testMatchExhaustiveReturn]
1909 # flags: --strict-equality --warn-unreachable
1910 def foo(value) -> int:
1911 match value:
1912 case "bar":
1913 return 1
1914 case _:
1915 return 2
1916
1917 [case testMatchNonExhaustiveReturn]
1918 # flags: --strict-equality --warn-unreachable
1919 def foo(value) -> int: # E: Missing return statement
1920 match value:
1921 case "bar":
1922 return 1
1923 case 2:
1924 return 2
1925
1926 [case testMatchMoreExhaustiveReturnCases]
1927 # flags: --strict-equality --warn-unreachable
1928 def g(value: int | None) -> int:
1929 match value:
1930 case int():
1931 return 0
1932 case None:
1933 return 1
1934
1935 def b(value: bool) -> int:
1936 match value:
1937 case True:
1938 return 2
1939 case False:
1940 return 3
1941
1942 [case testMatchMiscNonExhaustiveReturn]
1943 # flags: --strict-equality --warn-unreachable
1944 class C:
1945 a: int | str
1946
1947 def f1(value: int | str | None) -> int: # E: Missing return statement
1948 match value:
1949 case int():
1950 return 0
1951 case None:
1952 return 1
1953
1954 def f2(c: C) -> int: # E: Missing return statement
1955 match c:
1956 case C(a=int()):
1957 return 0
1958 case C(a=str()):
1959 return 1
1960
1961 def f3(x: list[str]) -> int: # E: Missing return statement
1962 match x:
1963 case [a]:
1964 return 0
1965 case [a, b]:
1966 return 1
1967
1968 def f4(x: dict[str, int]) -> int: # E: Missing return statement
1969 match x:
1970 case {'x': a}:
1971 return 0
1972
1973 def f5(x: bool) -> int: # E: Missing return statement
1974 match x:
1975 case True:
1976 return 0
1977 [builtins fixtures/dict.pyi]
1978
1979 [case testMatchNonExhaustiveError]
1980 # flags: --strict-equality --warn-unreachable
1981 from typing import NoReturn
1982 def assert_never(x: NoReturn) -> None: ...
1983
1984 def f(value: int) -> int: # E: Missing return statement
1985 match value:
1986 case 1:
1987 return 0
1988 case 2:
1989 return 1
1990 case o:
1991 assert_never(o) # E: Argument 1 to "assert_never" has incompatible type "int"; expected "Never"
1992
1993 [case testMatchExhaustiveNoError]
1994 # flags: --strict-equality --warn-unreachable
1995 from typing import NoReturn, Union, Literal
1996 def assert_never(x: NoReturn) -> None: ...
1997
1998 def f(value: Literal[1] | Literal[2]) -> int:
1999 match value:
2000 case 1:
2001 return 0
2002 case 2:
2003 return 1
2004 case o:
2005 assert_never(o) # E: Statement is unreachable
2006 [typing fixtures/typing-medium.pyi]
2007
2008 [case testMatchSequencePatternNegativeNarrowing]
2009 # flags: --strict-equality --warn-unreachable
2010 from typing import Literal, Union, Sequence, Tuple
2011
2012 m1: Sequence[int | str]
2013
2014 match m1:
2015 case [int()]:
2016 reveal_type(m1) # N: Revealed type is "typing.Sequence[builtins.int]"
2017 case r:
2018 reveal_type(m1) # N: Revealed type is "typing.Sequence[builtins.int | builtins.str]"
2019
2020 m2: Tuple[int | str]
2021
2022 match m2:
2023 case (int(),):
2024 reveal_type(m2) # N: Revealed type is "tuple[builtins.int]"
2025 case r2:
2026 reveal_type(m2) # N: Revealed type is "tuple[builtins.str]"
2027
2028 m3: Tuple[Union[int, str]]
2029
2030 match m3:
2031 case (1,):
2032 reveal_type(m3) # N: Revealed type is "tuple[Literal[1]]"
2033 case r2:
2034 reveal_type(m3) # N: Revealed type is "tuple[builtins.int | builtins.str]"
2035
2036 m4: Tuple[Literal[1], int]
2037
2038 match m4:
2039 case (1, 5):
2040 reveal_type(m4) # N: Revealed type is "tuple[Literal[1], Literal[5]]"
2041 case (1, 6):
2042 reveal_type(m4) # N: Revealed type is "tuple[Literal[1], Literal[6]]"
2043 case _:
2044 reveal_type(m4) # N: Revealed type is "tuple[Literal[1], builtins.int]"
2045
2046 m5: Tuple[Literal[1, 2], Literal["a", "b"]]
2047
2048 match m5:
2049 case (1, str()):
2050 reveal_type(m5) # N: Revealed type is "tuple[Literal[1], Literal['a'] | Literal['b']]"
2051 case _:
2052 reveal_type(m5) # N: Revealed type is "tuple[Literal[2], Literal['a'] | Literal['b']]"
2053
2054 m6: Tuple[Literal[1, 2], Literal["a", "b"]]
2055
2056 match m6:
2057 case (1, "a"):
2058 reveal_type(m6) # N: Revealed type is "tuple[Literal[1], Literal['a']]"
2059 case _:
2060 reveal_type(m6) # N: Revealed type is "tuple[Literal[1] | Literal[2], Literal['a'] | Literal['b']]"
2061
2062 [builtins fixtures/tuple.pyi]
2063
2064 [case testMatchSequenceWildcardRefutability]
2065 # flags: --strict-equality --warn-unreachable
2066 def f1(x: int | list[int]):
2067 match x:
2068 case [*foo]:
2069 reveal_type(x) # N: Revealed type is "builtins.list[builtins.int]"
2070 reveal_type(foo) # N: Revealed type is "builtins.list[builtins.int]"
2071 case _:
2072 reveal_type(x) # N: Revealed type is "builtins.int"
2073
2074 def f2(x: object):
2075 match x:
2076 case [*foo]:
2077 reveal_type(x) # N: Revealed type is "typing.Sequence[builtins.object]"
2078 reveal_type(foo) # N: Revealed type is "builtins.list[builtins.object]"
2079 case _:
2080 reveal_type(x) # N: Revealed type is "builtins.object"
2081
2082 def f3(x: int | list[int]):
2083 match x:
2084 case [1, *foo]:
2085 reveal_type(x) # N: Revealed type is "builtins.list[builtins.int]"
2086 reveal_type(foo) # N: Revealed type is "builtins.list[builtins.int]"
2087 case _:
2088 reveal_type(x) # N: Revealed type is "builtins.int | builtins.list[builtins.int]"
2089 [builtins fixtures/tuple.pyi]
2090
2091 [case testMatchSequenceTupleAsPattern]
2092 # flags: --strict-equality --warn-unreachable
2093
2094 def f1(x: tuple[list[int], list[int]]):
2095 match x:
2096 case _, []:
2097 reveal_type(x) # N: Revealed type is "tuple[builtins.list[builtins.int], builtins.list[builtins.int]]"
2098 case [], _:
2099 reveal_type(x) # N: Revealed type is "tuple[builtins.list[builtins.int], builtins.list[builtins.int]]"
2100 case _:
2101 reveal_type(x) # N: Revealed type is "tuple[builtins.list[builtins.int], builtins.list[builtins.int]]"
2102
2103 def f2(x: tuple[list[int], list[int]]):
2104 match x:
2105 case a, b:
2106 reveal_type(x) # N: Revealed type is "tuple[builtins.list[builtins.int], builtins.list[builtins.int]]"
2107 case [], _:
2108 reveal_type(x) # E: Statement is unreachable
2109 [builtins fixtures/tuple.pyi]
2110
2111 [case testMatchSequenceTupleRegression]
2112 # flags: --strict-equality --warn-unreachable
2113
2114 def f1(a: str | None, b: str | None):
2115 # https://github.com/python/mypy/issues/14731
2116 match (a, b):
2117 case (None, _) | (_, None):
2118 reveal_type(a) # N: Revealed type is "builtins.str | None"
2119 reveal_type(b) # N: Revealed type is "builtins.str | None"
2120 case (a, b):
2121 reveal_type(a) # N: Revealed type is "builtins.str"
2122 reveal_type(b) # N: Revealed type is "builtins.str"
2123
2124 def f2(x: tuple[int | str]):
2125 # https://github.com/python/mypy/issues/14833#issuecomment-1454768900
2126 match x:
2127 case (int(),):
2128 reveal_type(x) # N: Revealed type is "tuple[builtins.int]"
2129 case (str(),):
2130 reveal_type(x) # N: Revealed type is "tuple[builtins.str]"
2131 case _:
2132 reveal_type(x) # E: Statement is unreachable
2133
2134 def f4(x: tuple[int | str, str]):
2135 # https://github.com/python/mypy/issues/18792
2136 match x:
2137 case (int(), y):
2138 reveal_type(x) # N: Revealed type is "tuple[builtins.int, builtins.str]"
2139 case (str(), y):
2140 reveal_type(x) # N: Revealed type is "tuple[builtins.str, builtins.str]"
2141 case _:
2142 reveal_type(x) # E: Statement is unreachable
2143
2144 class Add(tuple[int, int]): ...
2145 class Const(int): ...
2146
2147 def f5(e: Add | Const) -> int:
2148 # https://github.com/python/mypy/issues/17139
2149 reveal_type(e) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.Add] | __main__.Const"
2150 match e:
2151 case Add((a, b)):
2152 reveal_type(e) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.Add]"
2153 return a + b
2154 case Const(x):
2155 reveal_type(e) # N: Revealed type is "__main__.Const"
2156 return x
2157 reveal_type(e) # E: Statement is unreachable
2158
2159 def f6(d1: list[str], d2: list[str]):
2160 # https://github.com/python/mypy/issues/19995
2161 match (d1, d2):
2162 case ([sym], _) | (_, [sym]):
2163 reveal_type(sym) # N: Revealed type is "builtins.str"
2164 [builtins fixtures/dict.pyi]
2165
2166
2167 [case testMatchTupleUnions]
2168 # flags: --strict-equality --warn-unreachable
2169 from typing_extensions import Unpack
2170
2171 m1: tuple[int, str] | None
2172 match m1:
2173 case (a1, b1):
2174 reveal_type(a1) # N: Revealed type is "builtins.int"
2175 reveal_type(b1) # N: Revealed type is "builtins.str"
2176
2177 m2: tuple[int, str] | tuple[float, str]
2178 match m2:
2179 case (a2, b2):
2180 reveal_type(a2) # N: Revealed type is "builtins.int | builtins.float"
2181 reveal_type(b2) # N: Revealed type is "builtins.str"
2182
2183 m3: tuple[int] | tuple[float, str]
2184 match m3:
2185 case (a3, b3):
2186 reveal_type(a3) # N: Revealed type is "builtins.float"
2187 reveal_type(b3) # N: Revealed type is "builtins.str"
2188
2189 m4: tuple[int] | list[str]
2190 match m4:
2191 case (a4, b4):
2192 reveal_type(a4) # N: Revealed type is "builtins.str"
2193 reveal_type(b4) # N: Revealed type is "builtins.str"
2194
2195 m5: tuple[int, Unpack[tuple[float, ...]]] | None
2196 match m5:
2197 case (a5, b5):
2198 reveal_type(a5) # N: Revealed type is "builtins.int"
2199 reveal_type(b5) # N: Revealed type is "builtins.float"
2200
2201 m6: tuple[int, Unpack[tuple[float, ...]]] | list[str]
2202 match m6:
2203 case (a6, b6):
2204 reveal_type(a6) # N: Revealed type is "builtins.int | builtins.str"
2205 reveal_type(b6) # N: Revealed type is "builtins.float | builtins.str"
2206
2207 m7: tuple[int, Unpack[tuple[float, ...]]] | tuple[str, str]
2208 match m7:
2209 case (a7, b7, *rest7):
2210 reveal_type(a7) # N: Revealed type is "builtins.int | builtins.str"
2211 reveal_type(b7) # N: Revealed type is "builtins.float | builtins.str"
2212 reveal_type(rest7) # N: Revealed type is "builtins.list[builtins.float]"
2213
2214 # verify that if we are unpacking, it will get the type of the sequence if the tuple is too short
2215 m8: tuple[int, str] | list[float]
2216 match m8:
2217 case (a8, b8, *rest8):
2218 reveal_type(a8) # N: Revealed type is "builtins.int | builtins.float"
2219 reveal_type(b8) # N: Revealed type is "builtins.str | builtins.float"
2220 reveal_type(rest8) # N: Revealed type is "builtins.list[builtins.float]"
2221
2222 m9: tuple[str, str, int] | tuple[str, str]
2223 match m9:
2224 case (a9, *rest9):
2225 reveal_type(a9) # N: Revealed type is "builtins.str"
2226 reveal_type(rest9) # N: Revealed type is "builtins.list[builtins.str | builtins.int] | builtins.list[builtins.str]"
2227
2228 [builtins fixtures/tuple.pyi]
2229
2230
2231 [case testMatchEnumSingleChoice]
2232 # flags: --strict-equality --warn-unreachable
2233 from enum import Enum
2234 from typing import NoReturn
2235
2236 def assert_never(x: NoReturn) -> None: ...
2237
2238 class Medal(Enum):
2239 GOLD = 1
2240
2241 def f(m: Medal) -> None:
2242 always_assigned: int | None = None
2243 match m:
2244 case Medal.GOLD:
2245 always_assigned = 1
2246 # Ideally, this should narrow to literal
2247 # However `expr_type = try_expanding_sum_type_to_union(coerce_to_literal(expr_type), None)`
2248 # in checker.py means we expand the type to a LiteralType and then because there is no
2249 # net change we don't end up inserting the LiteralType into the type map
2250 reveal_type(m) # N: Revealed type is "__main__.Medal"
2251 case _:
2252 assert_never(m) # E: Statement is unreachable
2253
2254 reveal_type(always_assigned) # N: Revealed type is "builtins.int"
2255 [builtins fixtures/bool.pyi]
2256
2257 [case testMatchLiteralPatternEnumNegativeNarrowing]
2258 # flags: --strict-equality --warn-unreachable
2259 from enum import Enum
2260 class Medal(Enum):
2261 gold = 1
2262 silver = 2
2263 bronze = 3
2264
2265 def f(m: Medal) -> int:
2266 match m:
2267 case Medal.gold:
2268 reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.gold]"
2269 return 0
2270 case _:
2271 reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.silver] | Literal[__main__.Medal.bronze]"
2272 return 1
2273
2274 def g(m: Medal) -> int:
2275 match m:
2276 case Medal.gold:
2277 reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.gold]"
2278 return 0
2279 case Medal.silver:
2280 reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.silver]"
2281 return 1
2282 case Medal.bronze:
2283 reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.bronze]"
2284 return 2
2285 [builtins fixtures/enum.pyi]
2286
2287 [case testMatchLiteralOrValuePattern]
2288 # flags: --strict-equality --warn-unreachable
2289 from typing import Literal
2290
2291 def test1(x: Literal[1,2,3]) -> None:
2292 match x:
2293 case 1:
2294 reveal_type(x) # N: Revealed type is "Literal[1]"
2295 case other:
2296 reveal_type(x) # N: Revealed type is "Literal[2] | Literal[3]"
2297
2298 def test2(x: Literal[1,2,3]) -> None:
2299 match x:
2300 case 1:
2301 reveal_type(x) # N: Revealed type is "Literal[1]"
2302 case 2:
2303 reveal_type(x) # N: Revealed type is "Literal[2]"
2304 case 3:
2305 reveal_type(x) # N: Revealed type is "Literal[3]"
2306 case other:
2307 1 # E: Statement is unreachable
2308
2309 def test3(x: Literal[1,2,3]) -> None:
2310 match x:
2311 case 1 | 3:
2312 reveal_type(x) # N: Revealed type is "Literal[1] | Literal[3]"
2313 case other:
2314 reveal_type(x) # N: Revealed type is "Literal[2]"
2315
2316 [case testMatchLiteralPatternEnumWithTypedAttribute]
2317 # flags: --strict-equality --warn-unreachable
2318 from enum import Enum
2319 from typing import NoReturn
2320 def assert_never(x: NoReturn) -> None: ...
2321
2322 class int:
2323 def __new__(cls, value: int): pass
2324
2325 class Medal(int, Enum):
2326 prize: str
2327
2328 def __new__(cls, value: int, prize: str) -> Medal:
2329 enum = int.__new__(cls, value)
2330 enum._value_ = value
2331 enum.prize = prize
2332 return enum
2333
2334 gold = (1, 'cash prize')
2335 silver = (2, 'sponsorship')
2336 bronze = (3, 'nothing')
2337
2338 m: Medal
2339
2340 match m:
2341 case Medal.gold:
2342 reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.gold]"
2343 case Medal.silver:
2344 reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.silver]"
2345 case Medal.bronze:
2346 reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.bronze]"
2347 case _ as unreachable:
2348 assert_never(unreachable) # E: Statement is unreachable
2349
2350 [builtins fixtures/tuple.pyi]
2351
2352 [case testMatchLiteralPatternFunctionalEnum]
2353 # flags: --strict-equality --warn-unreachable
2354 from enum import Enum
2355 from typing import NoReturn
2356 def assert_never(x: NoReturn) -> None: ...
2357
2358 Medal = Enum('Medal', 'gold silver bronze')
2359 m: Medal
2360
2361 match m:
2362 case Medal.gold:
2363 reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.gold]"
2364 case Medal.silver:
2365 reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.silver]"
2366 case Medal.bronze:
2367 reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.bronze]"
2368 case _ as unreachable:
2369 assert_never(unreachable) # E: Statement is unreachable
2370 [builtins fixtures/enum.pyi]
2371
2372 [case testMatchLiteralPatternEnumCustomEquals]
2373 # flags: --strict-equality --warn-unreachable
2374 from enum import Enum
2375 class Medal(Enum):
2376 gold = 1
2377 silver = 2
2378 bronze = 3
2379
2380 def __eq__(self, other) -> bool: ...
2381
2382 m: Medal
2383
2384 match m:
2385 case Medal.gold:
2386 reveal_type(m) # N: Revealed type is "__main__.Medal"
2387 case _:
2388 reveal_type(m) # N: Revealed type is "Literal[__main__.Medal.silver] | Literal[__main__.Medal.bronze]"
2389 [builtins fixtures/enum.pyi]
2390
2391 [case testMatchNarrowUsingPatternGuardSpecialCase]
2392 # flags: --strict-equality --warn-unreachable
2393 def f(x: int | str) -> int:
2394 match x:
2395 case x if isinstance(x, str):
2396 return 0
2397 case int():
2398 return 1
2399 [builtins fixtures/isinstance.pyi]
2400
2401 [case testMatchNarrowDownUnionPartially]
2402 # flags: --strict-equality --warn-unreachable
2403
2404 def f(x: int | str) -> None:
2405 match x:
2406 case int():
2407 return
2408 reveal_type(x) # N: Revealed type is "builtins.str"
2409
2410 def g(x: int | str | None) -> None:
2411 match x:
2412 case int() | None:
2413 return
2414 reveal_type(x) # N: Revealed type is "builtins.str"
2415
2416 def h(x: int | str | None) -> None:
2417 match x:
2418 case int() | str():
2419 return
2420 reveal_type(x) # N: Revealed type is "None"
2421
2422 [case testMatchNarrowDownUsingLiteralMatch]
2423 # flags: --strict-equality --warn-unreachable
2424 from enum import Enum
2425 class Medal(Enum):
2426 gold = 1
2427 silver = 2
2428
2429 def b1(x: bool) -> None:
2430 match x:
2431 case True:
2432 return
2433 reveal_type(x) # N: Revealed type is "Literal[False]"
2434
2435 def b2(x: bool) -> None:
2436 match x:
2437 case False:
2438 return
2439 reveal_type(x) # N: Revealed type is "Literal[True]"
2440
2441 def e1(x: Medal) -> None:
2442 match x:
2443 case Medal.gold:
2444 return
2445 reveal_type(x) # N: Revealed type is "Literal[__main__.Medal.silver]"
2446
2447 def e2(x: Medal) -> None:
2448 match x:
2449 case Medal.silver:
2450 return
2451 reveal_type(x) # N: Revealed type is "Literal[__main__.Medal.gold]"
2452
2453 def i(x: int) -> None:
2454 match x:
2455 case 1:
2456 return
2457 reveal_type(x) # N: Revealed type is "builtins.int"
2458
2459 def s(x: str) -> None:
2460 match x:
2461 case 'x':
2462 return
2463 reveal_type(x) # N: Revealed type is "builtins.str"
2464
2465 def union(x: str | bool) -> None:
2466 match x:
2467 case True:
2468 return
2469 reveal_type(x) # N: Revealed type is "builtins.str | Literal[False]"
2470 [builtins fixtures/tuple.pyi]
2471
2472 [case testMatchNarrowDownUnionUsingClassPattern]
2473 # flags: --strict-equality --warn-unreachable
2474
2475 class Foo: ...
2476 class Bar(Foo): ...
2477
2478 def test_1(bar: Bar) -> None:
2479 match bar:
2480 case Foo() as foo:
2481 reveal_type(foo) # N: Revealed type is "__main__.Bar"
2482
2483 def test_2(bar: Bar | str) -> None:
2484 match bar:
2485 case Foo() as foo:
2486 reveal_type(foo) # N: Revealed type is "__main__.Bar"
2487
2488
2489 [case testMatchAssertFalseToSilenceFalsePositives]
2490 # flags: --strict-equality --warn-unreachable
2491 class C:
2492 a: int | str
2493
2494 def f(c: C) -> int:
2495 match c:
2496 case C(a=int()):
2497 return 0
2498 case C(a=str()):
2499 return 1
2500 case _:
2501 assert False
2502
2503 def g(c: C) -> int:
2504 match c:
2505 case C(a=int()):
2506 return 0
2507 case C(a=str()):
2508 return 1
2509 assert False
2510
2511 [case testMatchAsPatternExhaustiveness]
2512 # flags: --strict-equality --warn-unreachable
2513 def f(x: int | str) -> int:
2514 match x:
2515 case int() as n:
2516 return n
2517 case str() as s:
2518 return 1
2519
2520 [case testMatchOrPatternExhaustiveness]
2521 # flags: --strict-equality --warn-unreachable
2522 from typing import NoReturn, Literal
2523 def assert_never(x: NoReturn) -> None: ...
2524
2525 Color = Literal["blue", "green", "red"]
2526 c: Color
2527
2528 match c:
2529 case "blue":
2530 reveal_type(c) # N: Revealed type is "Literal['blue']"
2531 case "green" | "notColor":
2532 reveal_type(c) # N: Revealed type is "Literal['green']"
2533 case _:
2534 assert_never(c) # E: Argument 1 to "assert_never" has incompatible type "Literal['red']"; expected "Never"
2535 [typing fixtures/typing-typeddict.pyi]
2536
2537 [case testMatchAsPatternIntersection]
2538 # flags: --strict-equality --warn-unreachable
2539 class A: pass
2540 class B: pass
2541 class C: pass
2542
2543 def f(x: A) -> None:
2544 match x:
2545 case B() as y:
2546 reveal_type(y) # N: Revealed type is "__main__.<subclass of "__main__.A" and "__main__.B">"
2547 case C() as y:
2548 reveal_type(y) # N: Revealed type is "__main__.<subclass of "__main__.A" and "__main__.C">"
2549 reveal_type(y) # N: Revealed type is "__main__.<subclass of "__main__.A" and "__main__.B"> | __main__.<subclass of "__main__.A" and "__main__.C">"
2550
2551 [case testMatchWithBreakAndContinue]
2552 # flags: --strict-equality --warn-unreachable
2553 def f(x: int | str | None) -> None:
2554 i = int()
2555 while i:
2556 match x:
2557 case int():
2558 continue
2559 case str():
2560 break
2561 reveal_type(x) # N: Revealed type is "None"
2562 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str | None"
2563
2564 [case testMatchNarrowDownWithStarred-skip]
2565 # flags: --strict-equality --warn-unreachable
2566 from typing import List
2567 def f(x: List[int] | int) -> None:
2568 match x:
2569 case [*y]:
2570 reveal_type(y) # N: Revealed type is "builtins.list[builtins.int]"
2571 return
2572 reveal_type(x) # N: Revealed type is "builtins.int"
2573 [builtins fixtures/list.pyi]
2574
2575 -- Misc
2576
2577 [case testMatchAndWithStatementScope]
2578 # flags: --strict-equality --warn-unreachable
2579 from m import A, B
2580
2581 with A() as x:
2582 pass
2583 with B() as x: \
2584 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
2585 pass
2586
2587 with A() as y:
2588 pass
2589 with B() as y: \
2590 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
2591 pass
2592
2593 with A() as z:
2594 pass
2595 with B() as z: \
2596 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
2597 pass
2598
2599 with A() as zz:
2600 pass
2601 with B() as zz: \
2602 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
2603 pass
2604
2605 match x:
2606 case str(y) as z:
2607 zz = y
2608
2609 [file m.pyi]
2610 from typing import Any
2611
2612 class A:
2613 def __enter__(self) -> A: ...
2614 def __exit__(self, x, y, z) -> None: ...
2615 class B:
2616 def __enter__(self) -> B: ...
2617 def __exit__(self, x, y, z) -> None: ...
2618
2619 [case testOverrideMatchArgs]
2620 # flags: --strict-equality --warn-unreachable
2621 class AST:
2622 __match_args__ = ()
2623
2624 class stmt(AST): ...
2625
2626 class AnnAssign(stmt):
2627 __match_args__ = ('target', 'annotation', 'value', 'simple')
2628 target: str
2629 annotation: int
2630 value: str
2631 simple: int
2632
2633 reveal_type(AST.__match_args__) # N: Revealed type is "tuple[()]"
2634 reveal_type(stmt.__match_args__) # N: Revealed type is "tuple[()]"
2635 reveal_type(AnnAssign.__match_args__) # N: Revealed type is "tuple[Literal['target']?, Literal['annotation']?, Literal['value']?, Literal['simple']?]"
2636
2637 AnnAssign.__match_args__ = ('a', 'b', 'c', 'd') # E: Cannot assign to "__match_args__"
2638 __match_args__ = 0
2639
2640 def f(x: AST) -> None:
2641 match x:
2642 case AST():
2643 reveal_type(x) # N: Revealed type is "__main__.AST"
2644 match x:
2645 case stmt():
2646 reveal_type(x) # N: Revealed type is "__main__.stmt"
2647 match x:
2648 case AnnAssign(a, b, c, d):
2649 reveal_type(a) # N: Revealed type is "builtins.str"
2650 reveal_type(b) # N: Revealed type is "builtins.int"
2651 reveal_type(c) # N: Revealed type is "builtins.str"
2652 [builtins fixtures/tuple.pyi]
2653
2654 [case testMatchReachableDottedNames]
2655 # flags: --strict-equality --warn-unreachable
2656 class Consts:
2657 BLANK = ""
2658 SPECIAL = "asdf"
2659
2660 def test_func(test_str: str) -> str:
2661 match test_str:
2662 case Consts.BLANK:
2663 return "blank"
2664 case Consts.SPECIAL:
2665 return "special"
2666 case _:
2667 return "other"
2668
2669
2670 [case testNoneTypeWarning]
2671 # flags: --strict-equality --warn-unreachable
2672 from types import NoneType
2673
2674 def foo(x: NoneType): # E: NoneType should not be used as a type, please use None instead
2675 reveal_type(x) # N: Revealed type is "None"
2676
2677 [builtins fixtures/tuple.pyi]
2678
2679 [case testMatchTupleInstanceUnionNoCrash]
2680 # flags: --strict-equality --warn-unreachable
2681 from typing import Union
2682
2683 def func(e: Union[str, tuple[str]]) -> None:
2684 match e:
2685 case (a,) if isinstance(a, str):
2686 reveal_type(a) # N: Revealed type is "builtins.str"
2687 [builtins fixtures/tuple.pyi]
2688
2689 [case testMatchTupleOptionalNoCrash]
2690 # flags: --strict-equality --warn-unreachable
2691 foo: tuple[int] | None
2692 match foo:
2693 case x,:
2694 reveal_type(x) # N: Revealed type is "builtins.int"
2695 [builtins fixtures/tuple.pyi]
2696
2697 [case testMatchUnionTwoTuples]
2698 # flags: --strict-equality --warn-unreachable
2699
2700 def main(var: tuple[int, int] | tuple[str, str]):
2701 match var:
2702 case (42, a):
2703 reveal_type(a) # N: Revealed type is "builtins.int"
2704 case ("yes", b):
2705 reveal_type(b) # N: Revealed type is "builtins.str"
2706
2707
2708 def main2(var: tuple[int, int] | tuple[str, str] | tuple[str, int]):
2709 match var:
2710 case (42, a):
2711 reveal_type(a) # N: Revealed type is "builtins.int"
2712 case ("yes", b):
2713 reveal_type(b) # N: Revealed type is "builtins.str | builtins.int"
2714 [builtins fixtures/tuple.pyi]
2715
2716 [case testMatchNamedAndKeywordsAreTheSame]
2717 # flags: --strict-equality --warn-unreachable
2718 from typing import Generic, Final, TypeVar, Union
2719 from dataclasses import dataclass
2720
2721 T = TypeVar("T")
2722
2723 class Regular:
2724 x: str
2725 y: int
2726 __match_args__ = ("x",)
2727 class ReversedOrder:
2728 x: int
2729 y: str
2730 __match_args__ = ("y",)
2731 class GenericRegular(Generic[T]):
2732 x: T
2733 __match_args__ = ("x",)
2734 class GenericWithFinal(Generic[T]):
2735 x: T
2736 __match_args__: Final = ("x",)
2737 class RegularSubtype(GenericRegular[str]): ...
2738
2739 @dataclass
2740 class GenericDataclass(Generic[T]):
2741 x: T
2742
2743 input_arg: Union[
2744 Regular,
2745 ReversedOrder,
2746 GenericRegular[str],
2747 GenericWithFinal[str],
2748 RegularSubtype,
2749 GenericDataclass[str],
2750 ]
2751
2752 # Positional:
2753 match input_arg:
2754 case Regular(a):
2755 reveal_type(a) # N: Revealed type is "builtins.str"
2756 case ReversedOrder(a):
2757 reveal_type(a) # N: Revealed type is "builtins.str"
2758 case GenericWithFinal(a):
2759 reveal_type(a) # N: Revealed type is "builtins.str"
2760 case RegularSubtype(a):
2761 reveal_type(a) # N: Revealed type is "builtins.str"
2762 case GenericRegular(a):
2763 reveal_type(a) # N: Revealed type is "builtins.str"
2764 case GenericDataclass(a):
2765 reveal_type(a) # N: Revealed type is "builtins.str"
2766
2767 # Keywords:
2768 match input_arg:
2769 case Regular(x=a):
2770 reveal_type(a) # N: Revealed type is "builtins.str"
2771 case ReversedOrder(x=b): # Order is different
2772 reveal_type(b) # N: Revealed type is "builtins.int"
2773 case GenericWithFinal(x=a):
2774 reveal_type(a) # N: Revealed type is "builtins.str"
2775 case RegularSubtype(x=a):
2776 reveal_type(a) # N: Revealed type is "builtins.str"
2777 case GenericRegular(x=a):
2778 reveal_type(a) # N: Revealed type is "builtins.str"
2779 case GenericDataclass(x=a):
2780 reveal_type(a) # N: Revealed type is "builtins.str"
2781 [builtins fixtures/dataclasses.pyi]
2782
2783 [case testMatchValueConstrainedTypeVar]
2784 # flags: --strict-equality --warn-unreachable
2785 from typing import TypeVar, Iterable
2786
2787 S = TypeVar("S", int, str)
2788
2789 def my_func(pairs: Iterable[tuple[S, S]]) -> None:
2790 for pair in pairs:
2791 reveal_type(pair) # N: Revealed type is "tuple[builtins.int, builtins.int]" \
2792 # N: Revealed type is "tuple[builtins.str, builtins.str]"
2793 match pair:
2794 case _:
2795 reveal_type(pair) # N: Revealed type is "tuple[builtins.int, builtins.int]" \
2796 # N: Revealed type is "tuple[builtins.str, builtins.str]"
2797 [builtins fixtures/tuple.pyi]
2798
2799 [case testPossiblyUndefinedMatch]
2800 # flags: --enable-error-code possibly-undefined --strict-equality --warn-unreachable
2801 def f0(x: int | str) -> int:
2802 match x:
2803 case int():
2804 y = 1
2805 return y # E: Name "y" may be undefined
2806
2807 def f1(a: object) -> None:
2808 match a:
2809 case [y]: pass
2810 case _:
2811 y = 1
2812 x = 2
2813 z = y
2814 z = x # E: Name "x" may be undefined
2815
2816 def f2(a: object) -> None:
2817 match a:
2818 case [[y] as x]: pass
2819 case {"k1": 1, "k2": x, "k3": y}: pass
2820 case [0, *x]:
2821 y = 2
2822 case _:
2823 y = 1
2824 x = [2]
2825 z = x
2826 z = y
2827
2828 def f3(a: object) -> None:
2829 y = 1
2830 match a:
2831 case [x]:
2832 y = 2
2833 # Note the missing `case _:`
2834 z = x # E: Name "x" may be undefined
2835 z = y
2836
2837 def f4(a: object) -> None:
2838 y = 1
2839 match a:
2840 case [x]:
2841 y = 2
2842 case _:
2843 assert False, "unsupported"
2844 z = x
2845 z = y
2846
2847 def f5(a: object) -> None:
2848 match a:
2849 case tuple(x): pass
2850 case _:
2851 return
2852 y = x
2853
2854 def f6(a: object) -> None:
2855 if int():
2856 y = 1
2857 match a:
2858 case _ if y is not None: # E: Name "y" may be undefined
2859 pass
2860 [builtins fixtures/tuple.pyi]
2861
2862 [case testPossiblyUndefinedMatchUnreachable]
2863 # flags: --enable-error-code possibly-undefined --strict-equality --warn-unreachable
2864 import typing
2865
2866 def f0(x: int) -> int:
2867 match x:
2868 case 1 if not typing.TYPE_CHECKING:
2869 pass
2870 case 2:
2871 y = 2
2872 case _:
2873 y = 3
2874 return y # No error.
2875
2876 def f1(x: int) -> int:
2877 match x:
2878 case 1 if not typing.TYPE_CHECKING:
2879 pass
2880 case 2:
2881 y = 2
2882 return y # E: Name "y" may be undefined
2883
2884 [typing fixtures/typing-medium.pyi]
2885
2886 [case testUsedBeforeDefMatchWalrus]
2887 # flags: --enable-error-code used-before-def --strict-equality --warn-unreachable
2888 import typing
2889
2890 def f0(x: int) -> None:
2891 a = y # E: Cannot determine type of "y" # E: Name "y" is used before definition
2892 match y := x:
2893 case 1:
2894 b = y
2895 case 2:
2896 c = y
2897 d = y
2898
2899 [case testTypeAliasWithNewUnionSyntaxAndNoneLeftOperand]
2900 # flags: --strict-equality --warn-unreachable
2901 from typing import overload
2902 class C:
2903 @overload
2904 def __init__(self) -> None: pass
2905 @overload
2906 def __init__(self, x: int) -> None: pass
2907 def __init__(self, x=0):
2908 pass
2909
2910 class D: pass
2911
2912 X = None | C
2913 Y = None | D
2914 [builtins fixtures/type.pyi]
2915
2916 [case testMatchStatementWalrus]
2917 # flags: --strict-equality --warn-unreachable
2918 class A:
2919 a = 1
2920
2921 def returns_a_or_none() -> A | None:
2922 return A()
2923
2924 def returns_a() -> A:
2925 return A()
2926
2927 def f() -> None:
2928 match x := returns_a_or_none():
2929 case A():
2930 reveal_type(x.a) # N: Revealed type is "builtins.int"
2931 reveal_type(x) # N: Revealed type is "__main__.A | None"
2932 match x := returns_a():
2933 case A():
2934 reveal_type(x.a) # N: Revealed type is "builtins.int"
2935 reveal_type(x) # N: Revealed type is "__main__.A"
2936 y = returns_a_or_none()
2937 match y:
2938 case A():
2939 reveal_type(y.a) # N: Revealed type is "builtins.int"
2940
2941 [case testNarrowedVariableInNestedModifiedInMatch]
2942 # flags: --strict-equality --warn-unreachable
2943 from typing import Optional
2944
2945 def match_stmt_error1(x: Optional[str]) -> None:
2946 if x is None:
2947 x = "a"
2948 def nested() -> str:
2949 return x # E: Incompatible return value type (got "str | None", expected "str")
2950 match object():
2951 case str(x):
2952 pass
2953 nested()
2954
2955 def foo(x): pass
2956
2957 def match_stmt_ok1(x: Optional[str]) -> None:
2958 if x is None:
2959 x = "a"
2960 def nested() -> str:
2961 return x
2962 match foo(x):
2963 case str(y):
2964 z = x
2965 nested()
2966
2967 def match_stmt_error2(x: Optional[str]) -> None:
2968 if x is None:
2969 x = "a"
2970 def nested() -> str:
2971 return x # E: Incompatible return value type (got "str | None", expected "str")
2972 match [None]:
2973 case [x]:
2974 pass
2975 nested()
2976
2977 def match_stmt_error3(x: Optional[str]) -> None:
2978 if x is None:
2979 x = "a"
2980 def nested() -> str:
2981 return x # E: Incompatible return value type (got "str | None", expected "str")
2982 match {'a': None}:
2983 case {'a': x}:
2984 pass
2985 nested()
2986
2987 def match_stmt_error4(x: Optional[list[str]]) -> None:
2988 if x is None:
2989 x = ["a"]
2990 def nested() -> list[str]:
2991 return x # E: Incompatible return value type (got "list[str] | None", expected "list[str]")
2992 match ["a"]:
2993 case [*x]:
2994 pass
2995 nested()
2996
2997 class C:
2998 a: str
2999
3000 def match_stmt_error5(x: Optional[str]) -> None:
3001 if x is None:
3002 x = "a"
3003 def nested() -> str:
3004 return x # E: Incompatible return value type (got "str | None", expected "str")
3005 match C():
3006 case C(a=x):
3007 pass
3008 nested()
3009 [builtins fixtures/tuple.pyi]
3010
3011 [case testMatchSubjectRedefinition]
3012 # flags: --allow-redefinition-old --strict-equality --warn-unreachable
3013 def transform1(a: str) -> int:
3014 ...
3015
3016 def transform2(a: int) -> str:
3017 ...
3018
3019 def redefinition_good(a: str):
3020 a = transform1(a)
3021
3022 match (a + 1):
3023 case _:
3024 ...
3025
3026
3027 def redefinition_bad(a: int):
3028 a = transform2(a)
3029
3030 match (a + 1): # E: Unsupported operand types for + ("str" and "int")
3031 case _:
3032 ...
3033
3034 [builtins fixtures/primitives.pyi]
3035
3036 [case testPatternMatchingClassPatternLocation]
3037 # flags: --strict-equality --warn-unreachable
3038 # See https://github.com/python/mypy/issues/15496
3039 from some_missing_lib import DataFrame, Series # type: ignore[import]
3040 from typing import TypeVar
3041
3042 T = TypeVar("T", Series, DataFrame)
3043
3044 def f(x: T) -> None:
3045 match x:
3046 case Series() | DataFrame(): # type: ignore[misc]
3047 pass
3048
3049 def f2(x: T) -> None:
3050 match x:
3051 case Series(): # type: ignore[misc]
3052 pass
3053 case DataFrame(): # type: ignore[misc]
3054 pass
3055 [builtins fixtures/primitives.pyi]
3056
3057 [case testMatchGuardReachability]
3058 # flags: --strict-equality --warn-unreachable
3059 def f1(e: int) -> int:
3060 match e:
3061 case x if True:
3062 return x
3063 case _:
3064 return 0 # E: Statement is unreachable
3065 e = 0 # E: Statement is unreachable
3066
3067
3068 def f2(e: int) -> int:
3069 match e:
3070 case x if bool():
3071 return x
3072 case _:
3073 return 0
3074 e = 0 # E: Statement is unreachable
3075
3076 def f3(e: int | str | bytes) -> int:
3077 match e:
3078 case x if isinstance(x, int):
3079 return x
3080 case [x]:
3081 return 0 # E: Statement is unreachable
3082 case str(x):
3083 return 0
3084 reveal_type(e) # N: Revealed type is "builtins.bytes"
3085 return 0
3086
3087 def f4(e: int | str | bytes) -> int:
3088 match e:
3089 case int(x):
3090 pass
3091 case [x]:
3092 return 0 # E: Statement is unreachable
3093 case x if isinstance(x, str):
3094 return 0
3095 reveal_type(e) # N: Revealed type is "builtins.int | builtins.bytes"
3096 return 0
3097 [builtins fixtures/primitives.pyi]
3098
3099 [case testMatchGuardAlwaysTrueAlwaysFalse]
3100 # flags: --warn-unreachable --always-true TRUEFLAG --always-false FALSEFLAG --strict-equality
3101 TRUEFLAG = False
3102 FALSEFLAG = True
3103
3104 def true_flag(e: int) -> None:
3105 match e:
3106 case _ if TRUEFLAG:
3107 pass
3108 case 0:
3109 # No error
3110 1 + "asdf"
3111
3112 def false_flag(e: int) -> None:
3113 match e:
3114 case _ if FALSEFLAG:
3115 # No error
3116 1 + "asdf"
3117
3118 [case testMatchSequencePatternVariadicTupleNotTooShort]
3119 # flags: --strict-equality --warn-unreachable
3120 from typing import Tuple
3121 from typing_extensions import Unpack
3122
3123 fm1: Tuple[int, int, Unpack[Tuple[str, ...]], int]
3124 match fm1:
3125 case [fa1, fb1, fc1]:
3126 reveal_type(fa1) # N: Revealed type is "builtins.int"
3127 reveal_type(fb1) # N: Revealed type is "builtins.int"
3128 reveal_type(fc1) # N: Revealed type is "builtins.int"
3129
3130 fm2: Tuple[int, int, Unpack[Tuple[str, ...]], int]
3131 match fm2:
3132 case [fa2, fb2]:
3133 reveal_type(fa2) # E: Statement is unreachable
3134 reveal_type(fb2)
3135
3136 fm3: Tuple[int, int, Unpack[Tuple[str, ...]], int]
3137 match fm3:
3138 case [fa3, fb3, fc3, fd3, fe3]:
3139 reveal_type(fa3) # N: Revealed type is "builtins.int"
3140 reveal_type(fb3) # N: Revealed type is "builtins.int"
3141 reveal_type(fc3) # N: Revealed type is "builtins.str"
3142 reveal_type(fd3) # N: Revealed type is "builtins.str"
3143 reveal_type(fe3) # N: Revealed type is "builtins.int"
3144
3145 m1: Tuple[int, Unpack[Tuple[str, ...]], int]
3146 match m1:
3147 case [a1, *b1, c1]:
3148 reveal_type(a1) # N: Revealed type is "builtins.int"
3149 reveal_type(b1) # N: Revealed type is "builtins.list[builtins.str]"
3150 reveal_type(c1) # N: Revealed type is "builtins.int"
3151
3152 m2: Tuple[int, Unpack[Tuple[str, ...]], int]
3153 match m2:
3154 case [a2, b2, *c2, d2, e2]:
3155 reveal_type(a2) # N: Revealed type is "builtins.int"
3156 reveal_type(b2) # N: Revealed type is "builtins.str"
3157 reveal_type(c2) # N: Revealed type is "builtins.list[builtins.str]"
3158 reveal_type(d2) # N: Revealed type is "builtins.str"
3159 reveal_type(e2) # N: Revealed type is "builtins.int"
3160
3161 m3: Tuple[int, int, Unpack[Tuple[str, ...]], int, int]
3162 match m3:
3163 case [a3, *b3, c3]:
3164 reveal_type(a3) # N: Revealed type is "builtins.int"
3165 reveal_type(b3) # N: Revealed type is "builtins.list[builtins.int | builtins.str]"
3166 reveal_type(c3) # N: Revealed type is "builtins.int"
3167 [builtins fixtures/tuple.pyi]
3168
3169 [case testMatchSequencePatternVariadicTuple]
3170 # flags: --strict-equality --warn-unreachable
3171 from typing_extensions import Unpack
3172
3173 def f1(m: tuple[int, Unpack[tuple[str, ...]], int]) -> None:
3174 match m:
3175 case (a1, b1):
3176 reveal_type(m) # N: Revealed type is "tuple[builtins.int, builtins.int]"
3177 case (a2, b2, c2):
3178 reveal_type(m) # N: Revealed type is "tuple[builtins.int, builtins.str, builtins.int]"
3179 case (a3, b3, c3, d3):
3180 reveal_type(m) # N: Revealed type is "tuple[builtins.int, builtins.str, builtins.str, builtins.int]"
3181 case (a4, *b4, c4):
3182 reveal_type(m) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[builtins.str, ...]], builtins.int]"
3183 case _:
3184 reveal_type(m) # E: Statement is unreachable
3185
3186
3187 def f2(m: tuple[int] | tuple[str, str] | tuple[int, Unpack[tuple[str, ...]], int]):
3188 match m:
3189 case (x,):
3190 reveal_type(m) # N: Revealed type is "tuple[builtins.int]"
3191 case (x, y):
3192 reveal_type(m) # N: Revealed type is "tuple[builtins.str, builtins.str] | tuple[builtins.int, builtins.int]"
3193 case (x, y, z):
3194 reveal_type(m) # N: Revealed type is "tuple[builtins.int, builtins.str, builtins.int]"
3195 case _:
3196 reveal_type(m) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[builtins.str, ...]], builtins.int]"
3197 [builtins fixtures/tuple.pyi]
3198
3199 [case testMatchSequencePatternTypeVarTupleNotTooShort]
3200 # flags: --strict-equality --warn-unreachable
3201 from typing import Tuple
3202 from typing_extensions import Unpack, TypeVarTuple
3203
3204 Ts = TypeVarTuple("Ts")
3205 def test(xs: Tuple[Unpack[Ts]]) -> None:
3206 fm1: Tuple[int, int, Unpack[Ts], int]
3207 match fm1:
3208 case [fa1, fb1, fc1]:
3209 reveal_type(fa1) # N: Revealed type is "builtins.int"
3210 reveal_type(fb1) # N: Revealed type is "builtins.int"
3211 reveal_type(fc1) # N: Revealed type is "builtins.int"
3212
3213 fm2: Tuple[int, int, Unpack[Ts], int]
3214 match fm2:
3215 case [fa2, fb2]:
3216 reveal_type(fa2) # E: Statement is unreachable
3217 reveal_type(fb2)
3218
3219 fm3: Tuple[int, int, Unpack[Ts], int]
3220 match fm3:
3221 case [fa3, fb3, fc3, fd3, fe3]:
3222 reveal_type(fa3) # N: Revealed type is "builtins.int"
3223 reveal_type(fb3) # N: Revealed type is "builtins.int"
3224 reveal_type(fc3) # N: Revealed type is "builtins.object"
3225 reveal_type(fd3) # N: Revealed type is "builtins.object"
3226 reveal_type(fe3) # N: Revealed type is "builtins.int"
3227
3228 m1: Tuple[int, Unpack[Ts], int]
3229 match m1:
3230 case [a1, *b1, c1]:
3231 reveal_type(a1) # N: Revealed type is "builtins.int"
3232 reveal_type(b1) # N: Revealed type is "builtins.list[builtins.object]"
3233 reveal_type(c1) # N: Revealed type is "builtins.int"
3234
3235 m2: Tuple[int, Unpack[Ts], int]
3236 match m2:
3237 case [a2, b2, *c2, d2, e2]:
3238 reveal_type(a2) # N: Revealed type is "builtins.int"
3239 reveal_type(b2) # N: Revealed type is "builtins.object"
3240 reveal_type(c2) # N: Revealed type is "builtins.list[builtins.object]"
3241 reveal_type(d2) # N: Revealed type is "builtins.object"
3242 reveal_type(e2) # N: Revealed type is "builtins.int"
3243
3244 m3: Tuple[int, int, Unpack[Ts], int, int]
3245 match m3:
3246 case [a3, *b3, c3]:
3247 reveal_type(a3) # N: Revealed type is "builtins.int"
3248 reveal_type(b3) # N: Revealed type is "builtins.list[builtins.object]"
3249 reveal_type(c3) # N: Revealed type is "builtins.int"
3250 [builtins fixtures/tuple.pyi]
3251
3252 [case testMatchSequencePatternTypeVarBoundNoCrash]
3253 # flags: --strict-equality --warn-unreachable
3254 # This was crashing: https://github.com/python/mypy/issues/18089
3255 from typing import TypeVar, Sequence, Any
3256
3257 T = TypeVar("T", bound=Sequence[Any])
3258
3259 def f(x: T) -> None:
3260 match x:
3261 case [_]:
3262 pass
3263 [builtins fixtures/tuple.pyi]
3264
3265 [case testMatchSequencePatternTypeVarBoundNarrows]
3266 # flags: --strict-equality --warn-unreachable
3267 from typing import TypeVar, Sequence
3268
3269 T = TypeVar("T", bound=Sequence[int | str])
3270
3271 def accept_seq_int(x: Sequence[int]): ...
3272
3273 def f(x: T) -> None:
3274 match x:
3275 case [1, 2]:
3276 accept_seq_int(x)
3277 case _:
3278 accept_seq_int(x) # E: Argument 1 to "accept_seq_int" has incompatible type "T"; expected "Sequence[int]"
3279 [builtins fixtures/tuple.pyi]
3280
3281 [case testNarrowingTypeVarMatch]
3282 # flags: --strict-equality --warn-unreachable
3283
3284 # https://github.com/python/mypy/issues/18126
3285 from typing import TypeVar
3286
3287 T = TypeVar("T")
3288
3289 def fn_case(arg: T) -> None:
3290 match arg:
3291 case None:
3292 return None
3293 return None
3294 [builtins fixtures/primitives.pyi]
3295
3296 [case testNoneCheckDoesNotMakeTypeVarOptionalMatch]
3297 # flags: --strict-equality --warn-unreachable
3298 from typing import TypeVar
3299
3300 T = TypeVar('T')
3301
3302 def foo(x: T) -> T:
3303 out = None
3304 out = x
3305 match out:
3306 case None:
3307 pass
3308 return out
3309
3310 [builtins fixtures/isinstance.pyi]
3311
3312 [case testMatchSequenceReachableFromAny]
3313 # flags: --strict-equality --warn-unreachable
3314 from typing import Any
3315
3316 def maybe_list(d: Any) -> int:
3317 match d:
3318 case []:
3319 return 0
3320 case [[_]]:
3321 return 1
3322 case [_]:
3323 return 1
3324 case _:
3325 return 2
3326
3327 def with_guard(d: Any) -> None:
3328 match d:
3329 case [s] if isinstance(s, str):
3330 reveal_type(s) # N: Revealed type is "builtins.str"
3331 match d:
3332 case (s,) if isinstance(s, str):
3333 reveal_type(s) # N: Revealed type is "builtins.str"
3334
3335 def nested_in_dict(d: dict[str, Any]) -> int:
3336 match d:
3337 case {"src": ["src"]}:
3338 return 1
3339 case _:
3340 return 0
3341
3342 [builtins fixtures/dict.pyi]
3343
3344 [case testMatchRebindsOuterFunctionName]
3345 # flags: --strict-equality --warn-unreachable
3346 from typing import Literal
3347
3348 def f() -> None:
3349 def x() -> tuple[Literal["test"]]: ...
3350
3351 match x():
3352 case (x,) if x == "test": # E: Incompatible types in capture pattern (pattern captures type "Literal['test']", variable has type "Callable[[], tuple[Literal['test']]]") \
3353 # E: Non-overlapping equality check (left operand type: "Callable[[], tuple[Literal['test']]]", right operand type: "Literal['test']")
3354 reveal_type(x) # E: Statement is unreachable
3355 case foo:
3356 foo
3357
3358 [builtins fixtures/dict.pyi]
3359
3360 [case testMatchRebindsInnerFunctionName]
3361 # flags: --strict-equality --warn-unreachable
3362 class Some:
3363 value: int | str
3364 __match_args__ = ("value",)
3365
3366 def fn1(x: Some | int | str) -> None:
3367 match x:
3368 case int():
3369 def value():
3370 return 1
3371 reveal_type(value) # N: Revealed type is "def () -> Any"
3372 case str():
3373 def value():
3374 return 1
3375 reveal_type(value) # N: Revealed type is "def () -> Any"
3376 case Some(value): # E: Incompatible types in capture pattern (pattern captures type "int | str", variable has type "Callable[[], Any]")
3377 pass
3378
3379 def fn2(x: Some | int | str) -> None:
3380 match x:
3381 case int():
3382 def value() -> str:
3383 return ""
3384 reveal_type(value) # N: Revealed type is "def () -> builtins.str"
3385 case str():
3386 def value() -> int: # E: All conditional function variants must have identical signatures \
3387 # N: Original: \
3388 # N: def value() -> str \
3389 # N: Redefinition: \
3390 # N: def value() -> int
3391 return 1
3392 reveal_type(value) # N: Revealed type is "def () -> builtins.str"
3393 case Some(value): # E: Incompatible types in capture pattern (pattern captures type "int | str", variable has type "Callable[[], str]")
3394 pass
3395 [builtins fixtures/dict.pyi]
3396
3397 [case testMatchFunctionCall]
3398 # flags: --strict-equality --warn-unreachable
3399
3400 def fn() -> int | str: ...
3401
3402 match fn():
3403 case str(s):
3404 reveal_type(s) # N: Revealed type is "builtins.str"
3405 case int(i):
3406 reveal_type(i) # N: Revealed type is "builtins.int"
3407 case other:
3408 other # E: Statement is unreachable
3409
3410 [case testMatchAttribute]
3411 # flags: --strict-equality --warn-unreachable
3412
3413 class A:
3414 foo: int | str
3415
3416 match A().foo:
3417 case str(s):
3418 reveal_type(s) # N: Revealed type is "builtins.str"
3419 case int(i):
3420 reveal_type(i) # N: Revealed type is "builtins.int"
3421 case other:
3422 other # E: Statement is unreachable
3423
3424 [case testMatchLiteral]
3425 # flags: --strict-equality --warn-unreachable
3426
3427 def int_literal() -> None:
3428 match 12:
3429 case 1 as s:
3430 reveal_type(s) # E: Statement is unreachable
3431 case int(i):
3432 reveal_type(i) # N: Revealed type is "Literal[12]?"
3433 case other:
3434 other # E: Statement is unreachable
3435
3436 def str_literal() -> None:
3437 match 'foo':
3438 case 'a' as s:
3439 reveal_type(s) # E: Statement is unreachable
3440 case str(i):
3441 reveal_type(i) # N: Revealed type is "Literal['foo']?"
3442 case other:
3443 other # E: Statement is unreachable
3444
3445 [case testMatchOperations]
3446 # flags: --strict-equality --warn-unreachable
3447
3448 x: int
3449 match -x:
3450 case -1 as s:
3451 reveal_type(s) # N: Revealed type is "Literal[-1]"
3452 case int(s):
3453 reveal_type(s) # N: Revealed type is "builtins.int"
3454 case other:
3455 other # E: Statement is unreachable
3456
3457 match 1 + 2:
3458 case 3 as s:
3459 reveal_type(s) # N: Revealed type is "Literal[3]"
3460 case int(s):
3461 reveal_type(s) # N: Revealed type is "builtins.int"
3462 case other:
3463 other # E: Statement is unreachable
3464
3465 match 1 > 2:
3466 case True as s:
3467 reveal_type(s) # N: Revealed type is "Literal[True]"
3468 case False as s:
3469 reveal_type(s) # N: Revealed type is "Literal[False]"
3470 case other:
3471 other # E: Statement is unreachable
3472 [builtins fixtures/ops.pyi]
3473
3474 [case testMatchDictItem]
3475 # flags: --strict-equality --warn-unreachable
3476
3477 m: dict[str, int | str]
3478 k: str
3479
3480 match m[k]:
3481 case str(s):
3482 reveal_type(s) # N: Revealed type is "builtins.str"
3483 case int(i):
3484 reveal_type(i) # N: Revealed type is "builtins.int"
3485 case other:
3486 other # E: Statement is unreachable
3487
3488 [builtins fixtures/dict.pyi]
3489
3490 [case testMatchLiteralValuePathological]
3491 # flags: --strict-equality --warn-unreachable
3492
3493 match 0:
3494 case 0 as i:
3495 reveal_type(i) # N: Revealed type is "Literal[0]?"
3496 case int(i):
3497 i # E: Statement is unreachable
3498 case other:
3499 other # E: Statement is unreachable
3500
3501 [case testMatchNamedTupleSequence]
3502 # flags: --strict-equality --warn-unreachable
3503 from typing import Any, NamedTuple
3504
3505 class T(NamedTuple):
3506 t: list[Any]
3507
3508 class K(NamedTuple):
3509 k: int
3510
3511 def f(t: T) -> None:
3512 match t:
3513 case T([K() as k]):
3514 reveal_type(k) # N: Revealed type is "tuple[builtins.int, fallback=__main__.K]"
3515 [builtins fixtures/tuple.pyi]
3516
3517 [case testMatchTypeObjectTypeVar]
3518 # flags: --strict-equality --warn-unreachable
3519 from typing import TypeVar
3520 import b
3521
3522 T_Choice = TypeVar("T_Choice", bound=b.One | b.Two)
3523
3524 def switch(choice: type[T_Choice]) -> None:
3525 match choice:
3526 case b.One:
3527 reveal_type(choice) # N: Revealed type is "def () -> b.One"
3528 reveal_type(choice()) # N: Revealed type is "b.One"
3529 case b.Two:
3530 reveal_type(choice) # N: Revealed type is "def () -> b.Two"
3531 reveal_type(choice()) # N: Revealed type is "b.Two"
3532 case _:
3533 reveal_type(choice) # N: Revealed type is "type[T_Choice`-1]"
3534 reveal_type(choice()) # N: Revealed type is "T_Choice`-1"
3535
3536 [file b.py]
3537 class One: ...
3538 class Two: ...
3539
3540 [builtins fixtures/tuple.pyi]
3541
3542 [case testNewRedefineMatchBasics]
3543 # flags: --allow-redefinition --strict-equality --warn-unreachable
3544
3545 def f1(x: int | str | list[bytes]) -> None:
3546 match x:
3547 case int():
3548 reveal_type(x) # N: Revealed type is "builtins.int"
3549 case str(y):
3550 reveal_type(y) # N: Revealed type is "builtins.str"
3551 case [y]:
3552 reveal_type(y) # N: Revealed type is "builtins.bytes"
3553 reveal_type(y) # N: Revealed type is "builtins.str | builtins.bytes"
3554
3555 [case testNewRedefineLoopWithMatch]
3556 # flags: --allow-redefinition --strict-equality --warn-unreachable
3557
3558 def f1() -> None:
3559 while True:
3560 x = object()
3561 match x:
3562 case str(y):
3563 pass
3564 case int():
3565 pass
3566 if int():
3567 continue
3568
3569 def f2() -> None:
3570 for x in [""]:
3571 match str():
3572 case "a":
3573 y = ""
3574 case "b":
3575 y = 1
3576 return
3577 reveal_type(y) # N: Revealed type is "builtins.str"
3578 [builtins fixtures/list.pyi]
3579
3580 [case testExhaustiveMatchNoFlag]
3581 # flags: --strict-equality --warn-unreachable
3582
3583 a: int = 5
3584 match a:
3585 case 1:
3586 pass
3587 case _:
3588 pass
3589
3590 b: str = "hello"
3591 match b:
3592 case "bye":
3593 pass
3594 case _:
3595 pass
3596
3597 [case testNonExhaustiveMatchNoFlag]
3598 # flags: --strict-equality --warn-unreachable
3599
3600 a: int = 5
3601 match a:
3602 case 1:
3603 pass
3604
3605 b: str = "hello"
3606 match b:
3607 case "bye":
3608 pass
3609
3610
3611 [case testExhaustiveMatchWithFlag]
3612 # flags: --enable-error-code exhaustive-match --strict-equality --warn-unreachable
3613
3614 a: int = 5
3615 match a:
3616 case 1:
3617 pass
3618 case _:
3619 pass
3620
3621 b: str = "hello"
3622 match b:
3623 case "bye":
3624 pass
3625 case _:
3626 pass
3627
3628 [case testNonExhaustiveMatchWithFlag]
3629 # flags: --enable-error-code exhaustive-match --strict-equality --warn-unreachable
3630
3631 a: int = 5
3632 match a: # E: Match statement has unhandled case for values of type "int" \
3633 # N: If match statement is intended to be non-exhaustive, add `case _: pass`
3634 case 1:
3635 pass
3636
3637 b: str = "hello"
3638 match b: # E: Match statement has unhandled case for values of type "str" \
3639 # N: If match statement is intended to be non-exhaustive, add `case _: pass`
3640 case "bye":
3641 pass
3642 [case testNonExhaustiveMatchEnumWithFlag]
3643 # flags: --enable-error-code exhaustive-match --strict-equality --warn-unreachable
3644
3645 import enum
3646
3647 class Color(enum.Enum):
3648 RED = 1
3649 BLUE = 2
3650 GREEN = 3
3651
3652 val: Color = Color.RED
3653
3654 match val: # E: Match statement has unhandled case for values of type "Literal[Color.GREEN]" \
3655 # N: If match statement is intended to be non-exhaustive, add `case _: pass`
3656 case Color.RED:
3657 a = "red"
3658 case Color.BLUE:
3659 a= "blue"
3660 [builtins fixtures/enum.pyi]
3661
3662 [case testExhaustiveMatchEnumWithFlag]
3663 # flags: --enable-error-code exhaustive-match --strict-equality --warn-unreachable
3664
3665 import enum
3666
3667 class Color(enum.Enum):
3668 RED = 1
3669 BLUE = 2
3670
3671 val: Color = Color.RED
3672
3673 match val:
3674 case Color.RED:
3675 a = "red"
3676 case Color.BLUE:
3677 a= "blue"
3678 [builtins fixtures/enum.pyi]
3679
3680 [case testNonExhaustiveMatchEnumMultipleMissingMatchesWithFlag]
3681 # flags: --enable-error-code exhaustive-match --strict-equality --warn-unreachable
3682
3683 import enum
3684
3685 class Color(enum.Enum):
3686 RED = 1
3687 BLUE = 2
3688 GREEN = 3
3689
3690 val: Color = Color.RED
3691
3692 match val: # E: Match statement has unhandled case for values of type "Literal[Color.BLUE, Color.GREEN]" \
3693 # N: If match statement is intended to be non-exhaustive, add `case _: pass`
3694 case Color.RED:
3695 a = "red"
3696 [builtins fixtures/enum.pyi]
3697
3698 [case testExhaustiveMatchEnumFallbackWithFlag]
3699 # flags: --enable-error-code exhaustive-match --strict-equality --warn-unreachable
3700
3701 import enum
3702
3703 class Color(enum.Enum):
3704 RED = 1
3705 BLUE = 2
3706 GREEN = 3
3707
3708 val: Color = Color.RED
3709
3710 match val:
3711 case Color.RED:
3712 a = "red"
3713 case _:
3714 a = "other"
3715 [builtins fixtures/enum.pyi]
3716
3717 # Fork of testMatchNarrowingUnionTypedDictViaIndex to check behaviour with exhaustive match flag
3718 [case testExhaustiveMatchNarrowingUnionTypedDictViaIndex]
3719 # flags: --enable-error-code exhaustive-match --strict-equality --warn-unreachable
3720
3721 from typing import Literal, TypedDict
3722
3723 class A(TypedDict):
3724 tag: Literal["a"]
3725 name: str
3726
3727 class B(TypedDict):
3728 tag: Literal["b"]
3729 num: int
3730
3731 d: A | B
3732 match d["tag"]: # E: Match statement has unhandled case for values of type "B" \
3733 # N: If match statement is intended to be non-exhaustive, add `case _: pass` \
3734 # E: Match statement has unhandled case for values of type "Literal['b']"
3735 case "a":
3736 reveal_type(d) # N: Revealed type is "TypedDict('__main__.A', {'tag': Literal['a'], 'name': builtins.str})"
3737 reveal_type(d["name"]) # N: Revealed type is "builtins.str"
3738 [typing fixtures/typing-typeddict.pyi]
3739
3740 [case testEnumTypeObjectMember]
3741 # flags: --strict-equality --warn-unreachable
3742 import enum
3743 from typing import NoReturn
3744
3745 def assert_never(x: NoReturn) -> None: ...
3746
3747 class ValueType(enum.Enum):
3748 INT = int
3749 STR = str
3750
3751 value_type: ValueType = ValueType.INT
3752
3753 match value_type:
3754 case ValueType.INT:
3755 pass
3756 case ValueType.STR:
3757 pass
3758 case _:
3759 assert_never(value_type) # E: Statement is unreachable
3760 [builtins fixtures/tuple.pyi]
3761
3762 [case testAssignmentToFinalInMatchCaseNotAllowed]
3763 # flags: --strict-equality --warn-unreachable
3764 from typing import Final
3765
3766 FOO: Final[int] = 10
3767
3768 val: int = 8
3769 match val:
3770 case FOO: # E: Cannot assign to final name "FOO"
3771 pass
3772
3773 [case testMatchExhaustivenessWithDeferral]
3774 # flags: --enable-error-code exhaustive-match --strict-equality --warn-unreachable
3775 from typing import Literal
3776 import unknown_module # E: Cannot find implementation or library stub for module named "unknown_module" \
3777 # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
3778
3779 def foo(e: Literal[0, 1]) -> None:
3780 match e:
3781 case 0:
3782 defer
3783 case 1:
3784 ...
3785
3786 defer = unknown_module.foo
3787
3788 [case testMatchErrorsIncorrectName]
3789 # flags: --strict-equality --warn-unreachable
3790 class A:
3791 pass
3792
3793 match 5:
3794 case A.blah(): # E: "type[A]" has no attribute "blah"
3795 pass
3796
3797 [case testMatchAllowsAnyClassArgsForAny]
3798 # flags: --strict-equality --warn-unreachable
3799 match 5:
3800 case BlahBlah(a, b): # E: Name "BlahBlah" is not defined
3801 reveal_type(a) # N: Revealed type is "Any"
3802 reveal_type(b) # N: Revealed type is "Any"
3803 case BlahBlah(c=c): # E: Name "BlahBlah" is not defined
3804 reveal_type(c) # N: Revealed type is "Any"
3805
3806 [case testMatchAllowsNoneTypeAsClass]
3807 # flags: --strict-equality --warn-unreachable
3808 import types
3809
3810 class V:
3811 X = types.NoneType
3812
3813 def fun(val: str | None):
3814 match val:
3815 case V.X():
3816 reveal_type(val) # N: Revealed type is "None"
3817
3818 match val:
3819 case types.NoneType():
3820 reveal_type(val) # N: Revealed type is "None"
3821 [builtins fixtures/tuple.pyi]
3822
3823 [case testMatchMappingRestErrorLocation]
3824 # flags: --strict-equality --warn-unreachable
3825 rest: list[int]
3826 data: list[int]
3827 match data:
3828 case [1, *rest]:
3829 ...
3830 config: dict[str, object]
3831 match config:
3832 case {"a": 1, **rest}: # E: Incompatible types in capture pattern (pattern captures type "dict[str, object]", variable has type "list[int]")
3833 ...
3834 [builtins fixtures/dict.pyi]
3835
3836 [case testMatchTypeNarrowing]
3837 # flags: --strict-equality --warn-unreachable
3838 import builtins
3839 import typing
3840 import types
3841
3842 def type_bare(field_type: type) -> str:
3843 match field_type:
3844 case builtins.int:
3845 reveal_type(field_type) # N: Revealed type is "def () -> builtins.int"
3846 ret = "foo"
3847 case builtins.str:
3848 reveal_type(field_type) # N: Revealed type is "def () -> builtins.str"
3849 ret = "foo"
3850 case builtins.bytes:
3851 reveal_type(field_type) # N: Revealed type is "def () -> builtins.bytes"
3852 ret = "foo"
3853 case builtins.bool:
3854 reveal_type(field_type) # N: Revealed type is "def () -> builtins.bool"
3855 ret = "foo"
3856 case types.NoneType:
3857 reveal_type(field_type) # N: Revealed type is "type[None]"
3858 ret = "foo"
3859 case _:
3860 reveal_type(field_type) # N: Revealed type is "builtins.type"
3861 return "bar"
3862 return ret
3863
3864 def type_any(field_type: type[typing.Any]) -> str:
3865 match field_type:
3866 case builtins.int:
3867 reveal_type(field_type) # N: Revealed type is "type[Any]"
3868 ret = "foo"
3869 case builtins.str:
3870 reveal_type(field_type) # N: Revealed type is "type[Any]"
3871 ret = "foo"
3872 case builtins.bytes:
3873 reveal_type(field_type) # N: Revealed type is "type[Any]"
3874 ret = "foo"
3875 case builtins.bool:
3876 reveal_type(field_type) # N: Revealed type is "type[Any]"
3877 ret = "foo"
3878 case types.NoneType:
3879 reveal_type(field_type) # N: Revealed type is "type[None]"
3880 ret = "foo"
3881 case _:
3882 reveal_type(field_type) # N: Revealed type is "type[Any]"
3883 return "bar"
3884 return ret
3885
3886 def type_object(field_type: type[object]) -> str:
3887 match field_type:
3888 case builtins.int:
3889 reveal_type(field_type) # N: Revealed type is "def () -> builtins.int"
3890 ret = "foo"
3891 case builtins.str:
3892 reveal_type(field_type) # N: Revealed type is "def () -> builtins.str"
3893 ret = "foo"
3894 case builtins.bytes:
3895 reveal_type(field_type) # N: Revealed type is "def () -> builtins.bytes"
3896 ret = "foo"
3897 case builtins.bool:
3898 reveal_type(field_type) # N: Revealed type is "def () -> builtins.bool"
3899 ret = "foo"
3900 case types.NoneType:
3901 reveal_type(field_type) # N: Revealed type is "type[None]"
3902 ret = "foo"
3903 case _:
3904 reveal_type(field_type) # N: Revealed type is "type[builtins.object]"
3905 return "bar"
3906 return ret
3907 [builtins fixtures/dict.pyi]
3908
3909
3910 [case testMatchFinalClass]
3911 # flags: --strict-equality --warn-unreachable
3912 from typing import final, NoReturn
3913
3914 def assert_never(x: NoReturn) -> NoReturn: ...
3915
3916 class Types:
3917
3918 @final
3919 class A:
3920 pass
3921
3922 @final
3923 class B:
3924 pass
3925
3926 def foo(cls: type[Types.A | Types.B]) -> None:
3927 match cls:
3928 case Types.A:
3929 reveal_type(cls) # N: Revealed type is "type[__main__.Types.A]"
3930 case Types.B:
3931 reveal_type(cls) # N: Revealed type is "type[__main__.Types.B]"
3932 case _:
3933 assert_never(cls)
3934
3935
3936 class TypeTypes:
3937 A: type[Types.A] = Types.A
3938 B: type[Types.B] = Types.B
3939
3940
3941 def bar(cls: type[Types.A | Types.B]) -> None:
3942 match cls:
3943 case TypeTypes.A:
3944 reveal_type(cls) # N: Revealed type is "type[__main__.Types.A]"
3945 case TypeTypes.B:
3946 reveal_type(cls) # N: Revealed type is "type[__main__.Types.B]"
3947 case _:
3948 assert_never(cls)
3949 [builtins fixtures/tuple.pyi]
3950
3951
3952 [case testMatchEnumOrdering]
3953 # flags: --strict-equality --warn-unreachable
3954 # Regression test for https://github.com/python/mypy/issues/21187
3955 import enum
3956 from typing import Literal
3957
3958 class DummyClass: ...
3959
3960 class MyEnum(enum.StrEnum):
3961 RELEVANT = "relevant"
3962 IGNORED = "ignored"
3963
3964 def dummy_class_then_enum(arg: DummyClass | Literal[MyEnum.RELEVANT]):
3965 match arg:
3966 case DummyClass():
3967 reveal_type(arg) # N: Revealed type is "__main__.DummyClass"
3968 case MyEnum.RELEVANT:
3969 reveal_type(arg) # N: Revealed type is "Literal[__main__.MyEnum.RELEVANT]"
3970 case _:
3971 pass # E: Statement is unreachable
3972
3973 def enum_then_dummy_class(arg: DummyClass | Literal[MyEnum.RELEVANT]):
3974 match arg:
3975 case MyEnum.RELEVANT:
3976 reveal_type(arg) # N: Revealed type is "Literal[__main__.MyEnum.RELEVANT]"
3977 case DummyClass():
3978 reveal_type(arg) # N: Revealed type is "__main__.DummyClass"
3979 case _:
3980 pass # E: Statement is unreachable
3981 [builtins fixtures/tuple.pyi]