Debian Codegraph @

test-data/unit/check-overloading.test

raw
1 -- Test cases for function overloading
2 [case testOverloadNotImportedNoCrash]
3
4 @overload
5 def f(a): pass
6 @overload
7 def f(a): pass
8 def f(a): pass
9 f(0)
10
11 @overload # E: Name "overload" is not defined
12 def g(a:int): pass
13 def g(a): pass # E: Name "g" already defined on line 9
14 g(0)
15
16 @something # E: Name "something" is not defined
17 def r(a:int): pass
18 def r(a): pass # E: Name "r" already defined on line 14
19 r(0)
20 [out]
21 main:2: error: Name "overload" is not defined
22 main:4: error: Name "f" already defined on line 2
23 main:4: error: Name "overload" is not defined
24 main:6: error: Name "f" already defined on line 2
25
26 [case testTypeCheckOverloadWithImplementation]
27 from typing import overload, Any
28 class A: pass
29 class B: pass
30
31 @overload
32 def f(x: 'A') -> 'B': ...
33 @overload
34 def f(x: 'B') -> 'A': ...
35
36 def f(x: Any) -> Any:
37 pass
38
39 reveal_type(f(A())) # N: Revealed type is "__main__.B"
40 reveal_type(f(B())) # N: Revealed type is "__main__.A"
41 [builtins fixtures/isinstance.pyi]
42
43 [case testTypingExtensionsOverload]
44 from typing import Any
45 from typing_extensions import overload
46 class A: pass
47 class B: pass
48
49 @overload
50 def f(x: 'A') -> 'B': ...
51 @overload
52 def f(x: 'B') -> 'A': ...
53
54 def f(x: Any) -> Any:
55 pass
56
57 reveal_type(f(A())) # N: Revealed type is "__main__.B"
58 reveal_type(f(B())) # N: Revealed type is "__main__.A"
59 [builtins fixtures/isinstance.pyi]
60
61 [case testOverloadNeedsImplementation]
62 from typing import overload, Any
63
64 class A: pass
65 class B: pass
66
67 @overload # E: An overloaded function outside a stub file must have an implementation
68 def f(x: 'A') -> 'B': ...
69 @overload
70 def f(x: 'B') -> 'A': ...
71
72 reveal_type(f(A())) # N: Revealed type is "__main__.B"
73 reveal_type(f(B())) # N: Revealed type is "__main__.A"
74 [builtins fixtures/isinstance.pyi]
75
76 [case testSingleOverloadNoImplementation]
77 from typing import overload, Any
78 @overload # E: Single overload definition, multiple required
79 def f(x: 'A') -> 'B': ...
80
81 class A: pass
82 class B: pass
83 [builtins fixtures/isinstance.pyi]
84
85 [case testOverloadByAnyOtherName]
86 from typing import overload as rose
87 from typing import Any
88 class A: pass
89 class B: pass
90
91 @rose
92 def f(x: 'A') -> 'B': ...
93 @rose
94 def f(x: 'B') -> 'A': ...
95
96 def f(x: Any) -> Any:
97 pass
98
99 reveal_type(f(A())) # N: Revealed type is "__main__.B"
100 reveal_type(f(B())) # N: Revealed type is "__main__.A"
101 [builtins fixtures/isinstance.pyi]
102
103 [case testTypeCheckOverloadWithDecoratedImplementation]
104 from typing import overload, Any
105
106 class A: pass
107 class B: pass
108
109 def deco(fun): ...
110
111 @overload
112 def f(x: 'A') -> 'B': ...
113 @overload
114 def f(x: 'B') -> 'A': ...
115
116 @deco
117 def f(x: Any) -> Any:
118 pass
119
120 reveal_type(f(A())) # N: Revealed type is "__main__.B"
121 reveal_type(f(B())) # N: Revealed type is "__main__.A"
122 [builtins fixtures/isinstance.pyi]
123
124 [case testOverloadDecoratedImplementationNotLast]
125 from typing import overload, Any
126
127 def deco(fun): ...
128
129 @overload
130 def f(x: 'A') -> 'B': ...
131
132 @deco # E: The implementation for an overloaded function must come last
133 def f(x: Any) -> Any:
134 pass
135
136 @overload
137 def f(x: 'B') -> 'A': ...
138
139 class A: pass
140 class B: pass
141 [builtins fixtures/isinstance.pyi]
142
143 [case testOverloadImplementationNotLast]
144 from typing import overload, Any
145
146 @overload
147 def f(x: 'A') -> 'B': ...
148
149 def f(x: Any) -> Any: # E: The implementation for an overloaded function must come last
150 pass
151
152 @overload
153 def f(x: 'B') -> 'A': ...
154
155 class A: pass
156 class B: pass
157 [builtins fixtures/isinstance.pyi]
158
159 [case testDecoratedRedefinitionIsNotOverload]
160 from typing import overload, Any
161
162 def deco(fun): ...
163
164 @deco
165 def f(x: 'A') -> 'B': ...
166 @deco # E: Name "f" already defined on line 5
167 def f(x: 'B') -> 'A': ...
168 @deco # E: Name "f" already defined on line 5
169 def f(x: Any) -> Any: ...
170
171 class A: pass
172 class B: pass
173 [builtins fixtures/isinstance.pyi]
174
175 [case testTypeCheckOverloadWithImplementationError]
176 from typing import overload, Any
177
178 class A: pass
179 class B: pass
180
181 @overload
182 def f(x: 'A') -> 'B': ...
183 @overload
184 def f(x: 'B') -> 'A': ...
185
186 def f(x: Any) -> Any:
187 foo = 1
188 if int():
189 foo = "bar" # E: Incompatible types in assignment (expression has type "str", variable has type "int")
190
191 @overload
192 def g(x: 'A') -> 'B': ...
193 @overload
194 def g(x: 'B') -> 'A': ...
195
196 def g(x):
197 foo = 1
198 if int():
199 foo = "bar"
200
201 reveal_type(f(A())) # N: Revealed type is "__main__.B"
202 reveal_type(f(B())) # N: Revealed type is "__main__.A"
203 [builtins fixtures/isinstance.pyi]
204
205 [case testTypeCheckOverloadWithUntypedImplAndMultipleVariants]
206 from typing import overload
207
208 @overload
209 def f(x: int) -> str: ...
210 @overload
211 def f(x: str) -> int: ... # E: Overloaded function signatures 2 and 3 overlap with incompatible return types
212 @overload
213 def f(x: object) -> str: ...
214 def f(x): ...
215
216 [case testTypeCheckOverloadWithImplTooSpecificArg]
217 from typing import overload, Any
218
219 class A: pass
220 class B: pass
221
222 a = A()
223
224 @overload
225 def f(x: 'A') -> 'B': ...
226 @overload
227 def f(x: 'B') -> 'A': ...
228
229 def f(x: 'A') -> Any: # E: Overloaded function implementation does not accept all possible parameters of signature 2
230 pass
231
232 reveal_type(f(A())) # N: Revealed type is "__main__.B"
233 reveal_type(f(B())) # N: Revealed type is "__main__.A"
234 [builtins fixtures/isinstance.pyi]
235
236 [case testTypeCheckOverloadImplOverlapVarArgsAndKwargs]
237 from __future__ import annotations
238 from typing import overload
239
240 @overload
241 def foo(x: int) -> None: ...
242 @overload
243 def foo(a: str, /) -> None: ...
244
245 def foo(*args: int | str, **kw: int) -> None:
246 pass
247 [builtins fixtures/tuple.pyi]
248
249 [case testTypeCheckOverloadImplOverlapVarArgsAndKwargsUnion]
250 from __future__ import annotations
251 from typing import overload
252
253 class Foo: ...
254
255 @overload
256 def foo(x: int) -> None: ...
257 @overload
258 def foo(*, x: Foo) -> None: ...
259 @overload
260 def foo(a: str, /) -> None: ...
261
262 def foo(*args: int | str, **kw: int | Foo) -> None:
263 pass
264 [builtins fixtures/tuple.pyi]
265
266
267 [case testTypeCheckOverloadImplOverlapVarArgsAndKwargsNever]
268 from __future__ import annotations
269 from typing import overload
270
271 @overload # E: Single overload definition, multiple required
272 def foo(x: int) -> None: ...
273
274 def foo(*args: int, **kw: str) -> None: # E: Overloaded function implementation does not accept all possible parameters of signature 1
275 pass
276 [builtins fixtures/tuple.pyi]
277
278
279 [case testTypeCheckOverloadWithImplTooSpecificRetType]
280 from typing import overload, Any
281
282 class A: pass
283 class B: pass
284
285 a = A()
286
287 @overload
288 def f(x: 'A') -> 'B': ...
289 @overload
290 def f(x: 'B') -> 'A': ...
291
292 def f(x: Any) -> 'B': # E: Overloaded function implementation cannot produce return type of signature 2
293 return B()
294
295 reveal_type(f(A())) # N: Revealed type is "__main__.B"
296 reveal_type(f(B())) # N: Revealed type is "__main__.A"
297
298 [builtins fixtures/isinstance.pyi]
299
300 [case testTypeCheckOverloadWithImplTypeVar]
301 from typing import overload, Any, TypeVar
302
303 T = TypeVar('T')
304
305 class A: pass
306 class B: pass
307
308 a = A()
309
310 @overload
311 def f(x: 'A') -> 'A': ...
312 @overload
313 def f(x: 'B') -> 'B': ...
314
315 def f(x: T) -> T:
316 ...
317
318 reveal_type(f(A())) # N: Revealed type is "__main__.A"
319 reveal_type(f(B())) # N: Revealed type is "__main__.B"
320
321 [builtins fixtures/isinstance.pyi]
322
323 [case testTypeCheckOverloadWithImplTypeVarProblems]
324 from typing import overload, Any, TypeVar, Union
325
326 T = TypeVar('T', bound='A')
327
328 class A: pass
329 class B: pass
330
331 a = A()
332
333 @overload
334 def f(x: 'A') -> 'A': ...
335 @overload
336 def f(x: 'B') -> 'B': ...
337
338 def f(x: Union[T, B]) -> T: # E: Overloaded function implementation cannot satisfy signature 2 due to inconsistencies in how they use type variables
339 ...
340
341 reveal_type(f(A())) # N: Revealed type is "__main__.A"
342 reveal_type(f(B())) # N: Revealed type is "__main__.B"
343
344 [builtins fixtures/isinstance.pyi]
345
346 [case testTypeCheckOverloadImplementationTypeVarWithValueRestriction]
347 from typing import overload, TypeVar, Union
348
349 class A: pass
350 class B: pass
351 class C: pass
352
353 T = TypeVar('T', A, B)
354
355 @overload
356 def foo(x: T) -> T: ...
357 @overload
358 def foo(x: C) -> int: ...
359 def foo(x: Union[A, B, C]) -> Union[A, B, int]:
360 if isinstance(x, C):
361 return 3
362 else:
363 return x
364
365 @overload
366 def bar(x: T) -> T: ...
367 @overload
368 def bar(x: C) -> int: ...
369 def bar(x: Union[T, C]) -> Union[T, int]:
370 if isinstance(x, C):
371 return 3
372 else:
373 return x
374
375 [builtins fixtures/isinstancelist.pyi]
376
377 [case testTypeCheckOverloadImplementationTypeVarDifferingUsage1]
378 from typing import overload, Union, List, TypeVar, Generic
379
380 T = TypeVar('T')
381
382 @overload
383 def foo(t: List[T]) -> T: ...
384 @overload
385 def foo(t: T) -> T: ...
386 def foo(t: Union[List[T], T]) -> T:
387 if isinstance(t, list):
388 return t[0]
389 else:
390 return t
391
392 class Wrapper(Generic[T]):
393 @overload
394 def foo(self, t: List[T]) -> T: ...
395 @overload
396 def foo(self, t: T) -> T: ...
397 def foo(self, t: Union[List[T], T]) -> T:
398 if isinstance(t, list):
399 return t[0]
400 else:
401 return t
402 [builtins fixtures/isinstancelist.pyi]
403
404 [case testTypeCheckOverloadImplementationTypeVarDifferingUsage2]
405 from typing import overload, Union, List, TypeVar, Generic
406
407 T = TypeVar('T')
408
409 # Note: this is unsafe when T = object
410 @overload
411 def foo(t: List[T], s: T) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
412 @overload
413 def foo(t: T, s: T) -> str: ...
414 def foo(t, s): pass
415
416 class Wrapper(Generic[T]):
417 @overload
418 def foo(self, t: List[T], s: T) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types \
419 # N: Flipping the order of overloads will fix this error
420 @overload
421 def foo(self, t: T, s: T) -> str: ...
422 def foo(self, t, s): pass
423
424 class Dummy(Generic[T]): pass
425
426 # Same root issue: why does the additional constraint bound T <: T
427 # cause the constraint solver to not infer T = object like it did in the
428 # first example?
429 @overload
430 def bar(d: Dummy[T], t: List[T], s: T) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types \
431 # N: Flipping the order of overloads will fix this error
432 @overload
433 def bar(d: Dummy[T], t: T, s: T) -> str: ...
434 def bar(d: Dummy[T], t, s): pass
435 [builtins fixtures/isinstancelist.pyi]
436
437 [case testTypeCheckOverloadedFunctionBody]
438 from foo import *
439 [file foo.pyi]
440 from typing import overload
441 @overload
442 def f(x: 'A'):
443 if int():
444 x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
445 x = A()
446 @overload
447 def f(x: 'B'):
448 if int():
449 x = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
450 x = B()
451 class A: pass
452 class B: pass
453 [out]
454
455 [case testTypeCheckOverloadedMethodBody]
456 from foo import *
457 [file foo.pyi]
458 from typing import overload
459 class A:
460 @overload
461 def f(self, x: 'A'):
462 if int():
463 x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
464 x = A()
465 @overload
466 def f(self, x: 'B'):
467 if int():
468 x = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
469 x = B()
470 class B: pass
471 [out]
472
473 [case testCallToOverloadedFunction]
474 from foo import *
475 [file foo.pyi]
476 from typing import overload
477 f(C()) # E: No overload variant of "f" matches argument type "C" \
478 # N: Possible overload variants: \
479 # N: def f(x: A) -> None \
480 # N: def f(x: B) -> None
481 f(A())
482 f(B())
483
484 @overload
485 def f(x: 'A') -> None: pass
486 @overload
487 def f(x: 'B') -> None: pass
488
489 class A: pass
490 class B: pass
491 class C: pass
492
493 [case testOverloadedFunctionReturnValue]
494 from foo import *
495 [file foo.pyi]
496 from typing import overload
497 a: A
498 b: B
499 if int():
500 b = f(a) # E: Incompatible types in assignment (expression has type "A", variable has type "B")
501 if int():
502 a = f(b) # E: Incompatible types in assignment (expression has type "B", variable has type "A")
503 if int():
504 a = f(a)
505 if int():
506 b = f(b)
507
508 @overload
509 def f(x: 'A') -> 'A': pass
510 @overload
511 def f(x: 'B') -> 'B': pass
512 class A: pass
513 class B: pass
514 [builtins fixtures/tuple.pyi]
515
516 [case testCallToOverloadedMethod]
517 from foo import *
518 [file foo.pyi]
519 from typing import overload
520 A().f(C()) # E: No overload variant of "f" of "A" matches argument type "C" \
521 # N: Possible overload variants: \
522 # N: def f(self, x: A) -> None \
523 # N: def f(self, x: B) -> None
524 A().f(A())
525 A().f(B())
526
527 class A:
528 @overload
529 def f(self, x: 'A') -> None: pass
530 @overload
531 def f(self, x: 'B') -> None: pass
532
533 class B: pass
534 class C: pass
535
536 [case testOverloadedMethodReturnValue]
537 from foo import *
538 [file foo.pyi]
539 from typing import overload
540 a: A
541 b: B
542 if int():
543 b = a.f(a) # E: Incompatible types in assignment (expression has type "A", variable has type "B")
544 if int():
545 a = a.f(b) # E: Incompatible types in assignment (expression has type "B", variable has type "A")
546 if int():
547 a = a.f(a)
548 if int():
549 b = a.f(b)
550
551 class A:
552 @overload
553 def f(self, x: 'A') -> 'A': pass
554 @overload
555 def f(self, x: 'B') -> 'B': pass
556 class B: pass
557 [builtins fixtures/tuple.pyi]
558
559 [case testOverloadsWithDifferentArgumentCounts]
560 from foo import *
561 [file foo.pyi]
562 from typing import overload
563 a: A
564 b: B
565 if int():
566 a = f(a)
567 if int():
568 b = f(a) # E: Incompatible types in assignment (expression has type "A", variable has type "B")
569 f(b) # E: No overload variant of "f" matches argument type "B" \
570 # N: Possible overload variants: \
571 # N: def f(x: A) -> A \
572 # N: def f(x: B, y: A) -> B
573 if int():
574 b = f(b, a)
575 if int():
576 a = f(b, a) # E: Incompatible types in assignment (expression has type "B", variable has type "A")
577 f(a, a) # E: No overload variant of "f" matches argument types "A", "A" \
578 # N: Possible overload variants: \
579 # N: def f(x: A) -> A \
580 # N: def f(x: B, y: A) -> B
581 f(b, b) # E: No overload variant of "f" matches argument types "B", "B" \
582 # N: Possible overload variants: \
583 # N: def f(x: A) -> A \
584 # N: def f(x: B, y: A) -> B
585
586 @overload
587 def f(x: 'A') -> 'A': pass
588 @overload
589 def f(x: 'B', y: 'A') -> 'B': pass
590 class A: pass
591 class B: pass
592 [builtins fixtures/tuple.pyi]
593
594 [case testGenericOverloadVariant]
595 from foo import *
596 [file foo.pyi]
597 from typing import overload, TypeVar, Generic
598 t = TypeVar('t')
599 ab: A[B]
600 ac: A[C]
601 b: B
602 c: C
603 if int():
604 b = f(ab)
605 c = f(ac)
606 b = f(ac) # E: Incompatible types in assignment (expression has type "C", variable has type "B")
607 b = f(b)
608 c = f(b) # E: Incompatible types in assignment (expression has type "B", variable has type "C")
609 @overload
610 def f(x: 'A[t]') -> t: pass
611 @overload
612 def f(x: 'B') -> 'B': pass
613 class A(Generic[t]): pass
614 class B: pass
615 class C: pass
616 [builtins fixtures/tuple.pyi]
617
618 [case testOverloadedInit]
619 from foo import *
620 [file foo.pyi]
621 from typing import overload
622 a: A
623 b: B
624 a = A(a)
625 a = A(b)
626 a = A(object()) # E: No overload variant of "A" matches argument type "object" \
627 # N: Possible overload variants: \
628 # N: def A(a: A) -> A \
629 # N: def A(b: B) -> A
630
631 class A:
632 @overload
633 def __init__(self, a: 'A') -> None: pass
634 @overload
635 def __init__(self, b: 'B') -> None: pass
636 class B: pass
637 [builtins fixtures/tuple.pyi]
638
639 [case testIntersectionTypeCompatibility]
640 from foo import *
641 [file foo.pyi]
642 from typing import overload, Callable
643 o: object
644 a: A
645
646 if int():
647 a = f # E: Incompatible types in assignment (expression has type overloaded function, variable has type "A")
648 if int():
649 o = f
650
651 @overload
652 def f(a: 'A') -> None: pass
653 @overload
654 def f(a: Callable[[], None]) -> None: pass
655 class A: pass
656
657 [case testCompatibilityOfIntersectionTypeObjectWithStdType]
658 from foo import *
659 [file foo.pyi]
660 from typing import overload
661 t: type
662 a: A
663
664 if int():
665 a = A # E: Incompatible types in assignment (expression has type "type[A]", variable has type "A")
666 t = A
667
668 class A:
669 @overload
670 def __init__(self, a: 'A') -> None: pass
671 @overload
672 def __init__(self, a: 'B') -> None: pass
673 class B: pass
674 [builtins fixtures/tuple.pyi]
675
676 [case testOverloadedGetitem]
677 from foo import *
678 [file foo.pyi]
679 from typing import overload
680 a: int
681 b: str
682 if int():
683 a = A()[a]
684 if int():
685 b = A()[a] # E: Incompatible types in assignment (expression has type "int", variable has type "str")
686 if int():
687 b = A()[b]
688 if int():
689 a = A()[b] # E: Incompatible types in assignment (expression has type "str", variable has type "int")
690
691 class A:
692 @overload
693 def __getitem__(self, a: int) -> int: pass
694 @overload
695 def __getitem__(self, b: str) -> str: pass
696 [builtins fixtures/tuple.pyi]
697
698 [case testOverloadedGetitemWithGenerics]
699 from foo import *
700 [file foo.pyi]
701 from typing import TypeVar, Generic, overload
702 t = TypeVar('t')
703 a: A
704 b: B
705 c: C[A]
706 if int():
707 a = c[a]
708 b = c[a] # E: Incompatible types in assignment (expression has type "A", variable has type "B")
709 if int():
710 a = c[b]
711 b = c[b] # E: Incompatible types in assignment (expression has type "A", variable has type "B")
712
713 class C(Generic[t]):
714 @overload
715 def __getitem__(self, a: 'A') -> t: pass
716 @overload
717 def __getitem__(self, b: 'B') -> t: pass
718 class A: pass
719 class B: pass
720 [builtins fixtures/tuple.pyi]
721
722 [case testImplementingOverloadedMethod]
723 from foo import *
724 [file foo.pyi]
725 from typing import overload
726 from abc import abstractmethod, ABCMeta
727
728 class I(metaclass=ABCMeta):
729 @overload
730 @abstractmethod
731 def f(self) -> None: pass
732 @overload
733 @abstractmethod
734 def f(self, a: 'A') -> None: pass
735 class A(I):
736 @overload
737 def f(self) -> None: pass
738 @overload
739 def f(self, a: 'A') -> None: pass
740
741 [case testOverloadWithFunctionType]
742 from foo import *
743 [file foo.pyi]
744 from typing import overload, Callable
745 class A: pass
746 @overload
747 def f(x: A) -> None: pass
748 @overload
749 def f(x: Callable[[], None]) -> None: pass
750
751 f(A())
752 [builtins fixtures/function.pyi]
753
754 [case testVarArgsOverload]
755 from foo import *
756 [file foo.pyi]
757 from typing import overload, Any
758 @overload
759 def f(x: 'A', *more: Any) -> 'A': pass
760 @overload
761 def f(x: 'B', *more: Any) -> 'A': pass
762 f(A())
763 f(A(), A, A)
764 f(B())
765 f(B(), B)
766 f(B(), B, B)
767 f(object()) # E: No overload variant of "f" matches argument type "object" \
768 # N: Possible overload variants: \
769 # N: def f(x: A, *more: Any) -> A \
770 # N: def f(x: B, *more: Any) -> A
771 class A: pass
772 class B: pass
773 [builtins fixtures/list.pyi]
774
775 [case testVarArgsOverload2]
776 from foo import *
777 [file foo.pyi]
778 from typing import overload
779 @overload
780 def f(x: 'A', *more: 'B') -> 'A': pass
781 @overload
782 def f(x: 'B', *more: 'A') -> 'A': pass
783 f(A(), B())
784 f(A(), B(), B())
785 f(A(), A(), B()) # E: No overload variant of "f" matches argument types "A", "A", "B" \
786 # N: Possible overload variants: \
787 # N: def f(x: A, *more: B) -> A \
788 # N: def f(x: B, *more: A) -> A
789 f(A(), B(), A()) # E: No overload variant of "f" matches argument types "A", "B", "A" \
790 # N: Possible overload variants: \
791 # N: def f(x: A, *more: B) -> A \
792 # N: def f(x: B, *more: A) -> A
793 class A: pass
794 class B: pass
795 [builtins fixtures/list.pyi]
796
797 [case testOverloadWithTypeObject]
798 from foo import *
799 [file foo.pyi]
800 from typing import overload
801 @overload
802 def f(a: 'A', t: type) -> None: pass
803 @overload
804 def f(a: 'B', t: type) -> None: pass
805 f(A(), B)
806 f(B(), A)
807 class A: pass
808 class B: pass
809 [builtins fixtures/function.pyi]
810
811 [case testOverloadedInitAndTypeObjectInOverload]
812 from foo import *
813 [file foo.pyi]
814 from typing import overload
815 @overload
816 def f(t: type) -> 'A': pass
817 @overload
818 def f(t: 'A') -> 'B': pass
819 a: A
820 b: B
821 if int():
822 a = f(A)
823 if int():
824 b = f(a)
825 if int():
826 b = f(A) # E: Incompatible types in assignment (expression has type "A", variable has type "B")
827 if int():
828 a = f(a) # E: Incompatible types in assignment (expression has type "B", variable has type "A")
829 class A:
830 @overload
831 def __init__(self) -> None: pass
832 @overload
833 def __init__(self, a: 'A') -> None: pass
834 class B:
835 pass
836 [builtins fixtures/tuple.pyi]
837
838 [case testOverlappingErasedSignatures]
839 from foo import *
840 [file foo.pyi]
841 from typing import overload, List
842 @overload
843 def f(a: List[int]) -> int: pass
844 @overload
845 def f(a: List[str]) -> int: pass
846 list_int = [] # type: List[int]
847 list_str = [] # type: List[str]
848 list_object = [] # type: List[object]
849 n = f(list_int)
850 m = f(list_str)
851 def p(): n, m # Prevent redefinition
852 n = 1
853 m = 1
854 n = 'x' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
855 m = 'x' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
856 f(list_object) # E: Argument 1 to "f" has incompatible type "list[object]"; expected "list[int]"
857 [builtins fixtures/list.pyi]
858
859 [case testOverlappingOverloadSignatures]
860 from foo import *
861 [file foo.pyi]
862 from typing import overload
863 class A: pass
864 class B(A): pass
865 @overload
866 def f(x: B) -> int: pass # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
867 @overload
868 def f(x: A) -> str: pass
869
870 [case testContravariantOverlappingOverloadSignatures]
871 from foo import *
872 [file foo.pyi]
873 from typing import overload
874 class A: pass
875 class B(A): pass
876 @overload
877 def f(x: A) -> A: pass
878 @overload
879 def f(x: B) -> B: pass # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
880
881 [case testPartiallyCovariantOverlappingOverloadSignatures]
882 from foo import *
883 [file foo.pyi]
884 from typing import overload
885 class A: pass
886 class B(A): pass
887 @overload
888 def f(x: B) -> A: pass # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
889 @overload
890 def f(x: A) -> B: pass
891
892 [case testPartiallyContravariantOverloadSignatures]
893 from foo import *
894 [file foo.pyi]
895 from typing import overload
896 class A: pass
897 class B(A): pass
898 @overload
899 def g(x: A) -> int: pass
900 @overload
901 def g(x: B) -> str: pass # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
902
903 [case testCovariantOverlappingOverloadSignatures]
904 from foo import *
905 [file foo.pyi]
906 from typing import overload
907 class A: pass
908 class B(A): pass
909 @overload
910 def g(x: B) -> B: pass
911 @overload
912 def g(x: A) -> A: pass
913
914 [case testCovariantOverlappingOverloadSignaturesWithSomeSameArgTypes]
915 from foo import *
916 [file foo.pyi]
917 from typing import overload
918 class A: pass
919 class B(A): pass
920 @overload
921 def g(x: int, y: B) -> B: pass
922 @overload
923 def g(x: int, y: A) -> A: pass
924
925 [case testCovariantOverlappingOverloadSignaturesWithAnyType]
926 from foo import *
927 [file foo.pyi]
928 from typing import Any, overload
929 @overload
930 def g(x: int) -> int: pass
931 @overload
932 def g(x: Any) -> Any: pass
933
934 [case testContravariantOverlappingOverloadSignaturesWithAnyType]
935 from foo import *
936 [file foo.pyi]
937 from typing import Any, overload
938 @overload
939 def g(x: Any) -> Any: pass
940 @overload
941 def g(x: int) -> int: pass # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
942
943 [case testOverloadedLtAndGtMethods]
944 from foo import *
945 [file foo.pyi]
946 from typing import overload
947 class A:
948 def __lt__(self, x: A) -> int: pass
949 def __gt__(self, x: A) -> int: pass
950 class B:
951 @overload
952 def __lt__(self, x: B) -> int: pass
953 @overload
954 def __lt__(self, x: A) -> int: pass
955 @overload
956 def __gt__(self, x: B) -> int: pass
957 @overload
958 def __gt__(self, x: A) -> int: pass
959 A() < A()
960 A() < B()
961 B() < A()
962 B() < B()
963 A() < object() # E: Unsupported operand types for < ("A" and "object")
964 B() < object() # E: No overload variant of "__lt__" of "B" matches argument type "object" \
965 # N: Possible overload variants: \
966 # N: def __lt__(self, B, /) -> int \
967 # N: def __lt__(self, A, /) -> int
968
969 [case testOverloadedForwardMethodAndCallingReverseMethod]
970 from foo import *
971 [file foo.pyi]
972 from typing import overload
973 class A:
974 @overload
975 def __add__(self, x: 'A') -> int: pass
976 @overload
977 def __add__(self, x: int) -> int: pass
978 class B:
979 def __radd__(self, x: A) -> int: pass
980 A() + A()
981 A() + 1
982 A() + B()
983 A() + '' # E: No overload variant of "__add__" of "A" matches argument type "str" \
984 # N: Possible overload variants: \
985 # N: def __add__(self, A, /) -> int \
986 # N: def __add__(self, int, /) -> int
987
988 [case testOverrideOverloadSwapped]
989 from foo import *
990 [file foo.pyi]
991 from typing import overload
992
993 class Parent:
994 @overload
995 def f(self, x: int) -> int: ...
996 @overload
997 def f(self, x: str) -> str: ...
998 class Child(Parent):
999 @overload # E: Signature of "f" incompatible with supertype "Parent" \
1000 # N: Overload variants must be defined in the same order as they are in "Parent"
1001 def f(self, x: str) -> str: ...
1002 @overload
1003 def f(self, x: int) -> int: ...
1004
1005 [case testOverrideOverloadSwappedWithExtraVariants]
1006 from foo import *
1007 [file foo.pyi]
1008 from typing import overload
1009
1010 class bool: pass
1011
1012 class Parent:
1013 @overload
1014 def f(self, x: int) -> int: ...
1015 @overload
1016 def f(self, x: str) -> str: ...
1017 class Child1(Parent):
1018 @overload # E: Signature of "f" incompatible with supertype "Parent" \
1019 # N: Overload variants must be defined in the same order as they are in "Parent"
1020 def f(self, x: bool) -> bool: ...
1021 @overload
1022 def f(self, x: str) -> str: ...
1023 @overload
1024 def f(self, x: int) -> int: ...
1025 class Child2(Parent):
1026 @overload # E: Signature of "f" incompatible with supertype "Parent" \
1027 # N: Overload variants must be defined in the same order as they are in "Parent"
1028 def f(self, x: str) -> str: ...
1029 @overload
1030 def f(self, x: bool) -> bool: ...
1031 @overload
1032 def f(self, x: int) -> int: ...
1033 class Child3(Parent):
1034 @overload # E: Signature of "f" incompatible with supertype "Parent" \
1035 # N: Overload variants must be defined in the same order as they are in "Parent"
1036 def f(self, x: str) -> str: ...
1037 @overload
1038 def f(self, x: int) -> int: ...
1039 @overload
1040 def f(self, x: bool) -> bool: ...
1041
1042 [case testOverrideOverloadSwappedWithAdjustedVariants]
1043 from foo import *
1044 [file foo.pyi]
1045 from typing import overload
1046
1047 class A: pass
1048 class B(A): pass
1049 class C(B): pass
1050
1051 class Parent:
1052 @overload
1053 def f(self, x: int) -> int: ...
1054 @overload
1055 def f(self, x: B) -> B: ...
1056 class Child1(Parent):
1057 @overload # Fail
1058 def f(self, x: A) -> B: ...
1059 @overload
1060 def f(self, x: int) -> int: ...
1061 class Child2(Parent):
1062 @overload # Fail
1063 def f(self, x: B) -> C: ...
1064 @overload
1065 def f(self, x: int) -> int: ...
1066 class Child3(Parent):
1067 @overload # Fail
1068 def f(self, x: B) -> A: ...
1069 @overload
1070 def f(self, x: int) -> int: ...
1071 [out]
1072 tmp/foo.pyi:13: error: Signature of "f" incompatible with supertype "Parent"
1073 tmp/foo.pyi:13: note: Overload variants must be defined in the same order as they are in "Parent"
1074 tmp/foo.pyi:18: error: Signature of "f" incompatible with supertype "Parent"
1075 tmp/foo.pyi:18: note: Overload variants must be defined in the same order as they are in "Parent"
1076 tmp/foo.pyi:23: error: Signature of "f" incompatible with supertype "Parent"
1077 tmp/foo.pyi:23: note: Superclass:
1078 tmp/foo.pyi:23: note: @overload
1079 tmp/foo.pyi:23: note: def f(self, x: int) -> int
1080 tmp/foo.pyi:23: note: @overload
1081 tmp/foo.pyi:23: note: def f(self, x: B) -> B
1082 tmp/foo.pyi:23: note: Subclass:
1083 tmp/foo.pyi:23: note: @overload
1084 tmp/foo.pyi:23: note: def f(self, x: B) -> A
1085 tmp/foo.pyi:23: note: @overload
1086 tmp/foo.pyi:23: note: def f(self, x: int) -> int
1087
1088 [case testOverrideOverloadedMethodWithMoreGeneralArgumentTypes]
1089 from foo import *
1090 [file foo.pyi]
1091 from typing import overload
1092
1093 class IntSub(int): pass
1094
1095 class StrSub(str): pass
1096 class A:
1097 @overload
1098 def f(self, x: IntSub) -> int: return 0
1099 @overload
1100 def f(self, x: StrSub) -> str: return ''
1101 class B(A):
1102 @overload
1103 def f(self, x: int) -> int: return 0
1104 @overload
1105 def f(self, x: str) -> str: return ''
1106 [out]
1107
1108 [case testOverrideOverloadedMethodWithMoreSpecificArgumentTypes]
1109 from foo import *
1110 [file foo.pyi]
1111 from typing import overload
1112
1113 class IntSub(int): pass
1114
1115 class StrSub(str): pass
1116 class A:
1117 @overload
1118 def f(self, x: int) -> int: return 0
1119 @overload
1120 def f(self, x: str) -> str: return ''
1121 class B(A):
1122 @overload # Fail
1123 def f(self, x: IntSub) -> int: return 0
1124 @overload
1125 def f(self, x: str) -> str: return ''
1126 class C(A):
1127 @overload # Fail
1128 def f(self, x: int) -> int: return 0
1129 @overload
1130 def f(self, x: StrSub) -> str: return ''
1131 class D(A):
1132 @overload
1133 def f(self, x: int) -> int: return 0
1134 @overload
1135 def f(self, x: str) -> str: return ''
1136 [out]
1137 tmp/foo.pyi:12: error: Signature of "f" incompatible with supertype "A"
1138 tmp/foo.pyi:12: note: Superclass:
1139 tmp/foo.pyi:12: note: @overload
1140 tmp/foo.pyi:12: note: def f(self, x: int) -> int
1141 tmp/foo.pyi:12: note: @overload
1142 tmp/foo.pyi:12: note: def f(self, x: str) -> str
1143 tmp/foo.pyi:12: note: Subclass:
1144 tmp/foo.pyi:12: note: @overload
1145 tmp/foo.pyi:12: note: def f(self, x: IntSub) -> int
1146 tmp/foo.pyi:12: note: @overload
1147 tmp/foo.pyi:12: note: def f(self, x: str) -> str
1148 tmp/foo.pyi:17: error: Signature of "f" incompatible with supertype "A"
1149 tmp/foo.pyi:17: note: Superclass:
1150 tmp/foo.pyi:17: note: @overload
1151 tmp/foo.pyi:17: note: def f(self, x: int) -> int
1152 tmp/foo.pyi:17: note: @overload
1153 tmp/foo.pyi:17: note: def f(self, x: str) -> str
1154 tmp/foo.pyi:17: note: Subclass:
1155 tmp/foo.pyi:17: note: @overload
1156 tmp/foo.pyi:17: note: def f(self, x: int) -> int
1157 tmp/foo.pyi:17: note: @overload
1158 tmp/foo.pyi:17: note: def f(self, x: StrSub) -> str
1159
1160 [case testOverloadingAndDucktypeCompatibility]
1161 from foo import *
1162 [file foo.pyi]
1163 from typing import overload, _promote
1164
1165 class A: pass
1166
1167 @_promote(A)
1168 class B: pass
1169
1170 @overload
1171 def f(n: B) -> B:
1172 return n
1173 @overload
1174 def f(n: A) -> A:
1175 return n
1176
1177 f(B()) + 'x' # E: Unsupported left operand type for + ("B")
1178 f(A()) + 'x' # E: Unsupported left operand type for + ("A")
1179 [typing fixtures/typing-medium.pyi]
1180
1181 [case testOverloadingAndIntFloatSubtyping]
1182 from foo import *
1183 [file foo.pyi]
1184 from typing import overload
1185 @overload
1186 def f(x: float) -> None: pass
1187 @overload
1188 def f(x: str) -> None: pass
1189 f(1.1)
1190 f('')
1191 f(1)
1192 f(()) # E: No overload variant of "f" matches argument type "tuple[()]" \
1193 # N: Possible overload variants: \
1194 # N: def f(x: float) -> None \
1195 # N: def f(x: str) -> None
1196 [builtins fixtures/primitives.pyi]
1197 [out]
1198
1199 [case testOverloadingVariableInputs]
1200 from foo import *
1201 [file foo.pyi]
1202 from typing import overload
1203 @overload
1204 def f(x: int, y: int) -> None: pass
1205 @overload
1206 def f(x: int) -> None: pass
1207 f(1)
1208 f(1, 2)
1209 z = (1, 2)
1210 f(*z)
1211 [builtins fixtures/primitives.pyi]
1212 [out]
1213
1214 [case testTypeInferenceSpecialCaseWithOverloading]
1215 from foo import *
1216 [file foo.pyi]
1217 from typing import overload
1218
1219 class A:
1220 def __add__(self, x: A) -> A: pass
1221 class B:
1222 def __radd__(self, x: A) -> B: pass
1223
1224 @overload
1225 def f(x: A) -> A: pass
1226 @overload
1227 def f(x: B) -> B: pass
1228
1229 f(A() + B())() # E: "B" not callable
1230
1231 [case testKeywordArgOverload]
1232 from foo import *
1233 [file foo.pyi]
1234 from typing import overload
1235 @overload
1236 def f(x: int, y: str) -> int: pass
1237 @overload
1238 def f(x: str, y: int) -> str: pass
1239 f(x=1, y='')() # E: "int" not callable
1240 f(y=1, x='')() # E: "str" not callable
1241
1242 [case testIgnoreOverloadVariantBasedOnKeywordArg]
1243 from foo import *
1244 [file foo.pyi]
1245 from typing import overload
1246 @overload
1247 def f(x: int) -> int: pass
1248 @overload
1249 def f(y: int) -> str: pass
1250 f(x=1)() # E: "int" not callable
1251 f(y=1)() # E: "str" not callable
1252
1253 [case testOverloadWithTupleVarArg]
1254 from foo import *
1255 [file foo.pyi]
1256 from typing import overload
1257 @overload
1258 def f(x: int, y: str) -> int: pass
1259 @overload
1260 def f(*x: str) -> str: pass
1261 f(*(1,))() # E: No overload variant of "f" matches argument type "tuple[int]" \
1262 # N: Possible overload variants: \
1263 # N: def f(x: int, y: str) -> int \
1264 # N: def f(*x: str) -> str
1265 f(*('',))() # E: "str" not callable
1266 f(*(1, ''))() # E: "int" not callable
1267 f(*(1, '', 1))() # E: No overload variant of "f" matches argument type "tuple[int, str, int]" \
1268 # N: Possible overload variants: \
1269 # N: def f(x: int, y: str) -> int \
1270 # N: def f(*x: str) -> str
1271 [builtins fixtures/tuple.pyi]
1272
1273 [case testPreferExactSignatureMatchInOverload]
1274 # flags: --no-strict-optional
1275 from foo import *
1276 [file foo.pyi]
1277 from typing import overload, List
1278 @overload
1279 def f(x: int, y: List[int] = None) -> int: pass
1280 @overload
1281 def f(x: int, y: List[str] = None) -> int: pass
1282 f(y=[1], x=0)() # E: "int" not callable
1283 f(y=[''], x=0)() # E: "int" not callable
1284 a = f(y=[['']], x=0) # E: List item 0 has incompatible type "list[str]"; expected "int"
1285 reveal_type(a) # N: Revealed type is "builtins.int"
1286 [builtins fixtures/list.pyi]
1287
1288 [case testOverloadWithDerivedFromAny]
1289 from foo import *
1290 [file foo.pyi]
1291 from typing import Any, overload
1292 Base = None # type: Any
1293
1294 class C:
1295 @overload
1296 def __init__(self, a: str) -> None: pass
1297 @overload
1298 def __init__(self, a: int) -> None: pass
1299
1300 class Derived(Base):
1301 def to_dict(self) -> C:
1302 return C(self) # fails without the fix for #1363
1303 C(Derived()) # fails without the hack
1304 C(Base()) # Always ok
1305
1306 [case testOverloadWithBoundedTypeVar]
1307 from foo import *
1308 [file foo.pyi]
1309 from typing import overload, TypeVar
1310 T = TypeVar('T', bound=str)
1311 @overload
1312 def f(x: T) -> T: pass
1313 @overload
1314 def f(x: int) -> bool: pass
1315 class mystr(str): pass
1316
1317 f('x')() # E: "str" not callable
1318 f(1)() # E: "bool" not callable
1319 f(1.1) # E: No overload variant of "f" matches argument type "float" \
1320 # N: Possible overload variants: \
1321 # N: def [T: str] f(x: T) -> T \
1322 # N: def f(x: int) -> bool
1323 f(mystr())() # E: "mystr" not callable
1324 [builtins fixtures/primitives.pyi]
1325
1326 [case testOverloadedCallWithVariableTypes]
1327 from foo import *
1328 [file foo.pyi]
1329 from typing import overload, TypeVar, List
1330 T = TypeVar('T', bound=str)
1331 @overload
1332 def f(x: T) -> T: pass
1333 @overload
1334 def f(x: List[T]) -> None: pass
1335 class mystr(str): pass
1336
1337 U = TypeVar('U', bound=mystr)
1338 V = TypeVar('V')
1339 def g(x: U, y: V) -> None:
1340 f(x)() # E: "mystr" not callable
1341 f(y) # E: No overload variant of "f" matches argument type "V" \
1342 # N: Possible overload variants: \
1343 # N: def [T: str] f(x: T) -> T \
1344 # N: def [T: str] f(x: list[T]) -> None
1345 a = f([x])
1346 reveal_type(a) # N: Revealed type is "None"
1347 f([y]) # E: Value of type variable "T" of "f" cannot be "V"
1348 f([x, y]) # E: Value of type variable "T" of "f" cannot be "object"
1349 [builtins fixtures/list.pyi]
1350 [out]
1351
1352 [case testOverloadOverlapWithTypeVars]
1353 from foo import *
1354 [file foo.pyi]
1355 from typing import overload, TypeVar, Sequence, List
1356 T = TypeVar('T', bound=str)
1357 @overload
1358 def f(x: Sequence[T]) -> None: pass
1359 @overload
1360 def f(x: Sequence[int]) -> int: pass
1361
1362 @overload
1363 def g(x: Sequence[T]) -> None: pass
1364 @overload
1365 def g(x: Sequence[str]) -> int: pass # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
1366
1367 @overload
1368 def h(x: Sequence[str]) -> int: pass
1369 @overload
1370 def h(x: Sequence[T]) -> None: pass # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
1371
1372 # Safety of this highly depends on the implementation, so we lean towards being silent.
1373 @overload
1374 def i(x: List[str]) -> int: pass
1375 @overload
1376 def i(x: List[T]) -> None: pass
1377 [builtins fixtures/list.pyi]
1378
1379 [case testOverloadOverlapWithTypeVarsWithValues]
1380 from foo import *
1381 [file foo.pyi]
1382 from typing import overload, TypeVar
1383 AnyStr = TypeVar('AnyStr', bytes, str)
1384
1385 @overload
1386 def f(x: int) -> int: pass
1387 @overload
1388 def f(x: AnyStr) -> str: pass
1389
1390 f(1)() # E: "int" not callable
1391 f('1')() # E: "str" not callable
1392 f(b'1')() # E: "str" not callable
1393 f(1.0) # E: No overload variant of "f" matches argument type "float" \
1394 # N: Possible overload variants: \
1395 # N: def f(x: int) -> int \
1396 # N: def [AnyStr: (bytes, str)] f(x: AnyStr) -> str
1397
1398 @overload
1399 def g(x: AnyStr, *a: AnyStr) -> None: pass
1400 @overload
1401 def g(x: int, *a: AnyStr) -> None: pass
1402
1403 g('foo')
1404 g('foo', 'bar')
1405 g('foo', b'bar') # E: Value of type variable "AnyStr" of "g" cannot be "Sequence[object]"
1406 g(1)
1407 g(1, 'foo')
1408 g(1, 'foo', b'bar') # E: Value of type variable "AnyStr" of "g" cannot be "Sequence[object]"
1409 [builtins fixtures/primitives.pyi]
1410
1411 [case testOverloadOverlapWithTypeVarsWithValuesOrdering]
1412 from foo import *
1413 [file foo.pyi]
1414 from typing import overload, TypeVar
1415 AnyStr = TypeVar('AnyStr', bytes, str)
1416
1417 @overload
1418 def f(x: AnyStr) -> AnyStr: pass
1419 @overload
1420 def f(x: str) -> str: pass # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
1421
1422 @overload
1423 def g(x: str) -> str: pass
1424 @overload
1425 def g(x: AnyStr) -> AnyStr: pass
1426 [builtins fixtures/primitives.pyi]
1427
1428 [case testOverloadsUsingAny]
1429 from typing import overload, List, Any, Union
1430
1431 @overload
1432 def foo(x: List[int]) -> int: ...
1433 @overload
1434 def foo(x: List[str]) -> str: ...
1435 def foo(x): pass
1436
1437 a: List[int]
1438 b: List[str]
1439 c: List[Any]
1440 d: Union[List[int], List[str]]
1441 e: List[bool]
1442 f: List[object]
1443 g: List[Union[int, str]]
1444
1445 reveal_type(foo(a))
1446 reveal_type(foo(b))
1447 reveal_type(foo(c))
1448 reveal_type(foo(d))
1449 foo(e)
1450 foo(f)
1451 foo(g)
1452
1453 [builtins fixtures/list.pyi]
1454 [out]
1455 main:17: note: Revealed type is "builtins.int"
1456 main:18: note: Revealed type is "builtins.str"
1457 main:19: note: Revealed type is "Any"
1458 main:20: note: Revealed type is "builtins.int | builtins.str"
1459 main:21: error: Argument 1 to "foo" has incompatible type "list[bool]"; expected "list[int]"
1460 main:21: note: "list" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
1461 main:21: note: Consider using "Sequence" instead, which is covariant
1462 main:22: error: Argument 1 to "foo" has incompatible type "list[object]"; expected "list[int]"
1463 main:23: error: Argument 1 to "foo" has incompatible type "list[int | str]"; expected "list[int]"
1464
1465 [case testOverloadAgainstEmptyCollections]
1466 from typing import overload, List
1467
1468 @overload
1469 def f(x: List[int]) -> int: ...
1470 @overload
1471 def f(x: List[str]) -> str: ...
1472 def f(x): pass
1473
1474 reveal_type(f([])) # N: Revealed type is "builtins.int"
1475 [builtins fixtures/list.pyi]
1476
1477 [case testOverloadAgainstEmptyCovariantCollections]
1478 from typing import overload, TypeVar, Generic
1479
1480 T = TypeVar('T', covariant=True)
1481 class Wrapper(Generic[T]): pass
1482
1483 class A: pass
1484 class B(A): pass
1485 class C: pass
1486
1487 @overload
1488 def f(x: Wrapper[A]) -> int: ...
1489 @overload
1490 def f(x: Wrapper[C]) -> str: ...
1491 def f(x): pass
1492
1493 reveal_type(f(Wrapper())) # N: Revealed type is "builtins.int"
1494 reveal_type(f(Wrapper[C]())) # N: Revealed type is "builtins.str"
1495 reveal_type(f(Wrapper[B]())) # N: Revealed type is "builtins.int"
1496
1497 [case testOverlappingOverloadCounting]
1498 from foo import *
1499 [file foo.pyi]
1500 from typing import overload
1501 class A: pass
1502 class B(A): pass
1503 @overload
1504 def f(x: int) -> None: pass
1505 @overload
1506 def f(x: B) -> str: pass # E: Overloaded function signatures 2 and 3 overlap with incompatible return types
1507 @overload
1508 def f(x: A) -> int: pass
1509
1510 [case testOverloadWithTupleMatchingTypeVar]
1511 from foo import *
1512 [file foo.pyi]
1513 from typing import TypeVar, Generic, Tuple, overload
1514
1515 T = TypeVar('T')
1516
1517 class A(Generic[T]):
1518 @overload
1519 def f(self, arg: T) -> None:
1520 pass
1521 @overload
1522 def f(self, arg: T, default: int) -> None:
1523 pass
1524
1525 b = A() # type: A[Tuple[int, int]]
1526 b.f((0, 0))
1527 b.f((0, '')) # E: Argument 1 to "f" of "A" has incompatible type "tuple[int, str]"; expected "tuple[int, int]"
1528 [builtins fixtures/tuple.pyi]
1529
1530 [case testSingleOverloadStub]
1531 from foo import *
1532 [file foo.pyi]
1533 from typing import overload
1534 @overload
1535 def f(a: int) -> None: pass
1536 def f(a: int) -> None: pass
1537 [out]
1538 tmp/foo.pyi:2: error: Single overload definition, multiple required
1539 tmp/foo.pyi:4: error: An implementation for an overloaded function is not allowed in a stub file
1540
1541 [case testSingleOverload2]
1542 from foo import *
1543 [file foo.pyi]
1544 from typing import overload
1545 def f(a: int) -> None: pass
1546 @overload
1547 def f(a: str) -> None: pass
1548 [out]
1549 tmp/foo.pyi:3: error: Name "f" already defined on line 2
1550 tmp/foo.pyi:3: error: Single overload definition, multiple required
1551
1552 [case testNonconsecutiveOverloads]
1553 from foo import *
1554 [file foo.pyi]
1555 from typing import overload
1556 @overload
1557 def f(a: int) -> None: pass
1558 1
1559 @overload
1560 def f(a: str) -> None: pass
1561 [out]
1562 tmp/foo.pyi:2: error: Single overload definition, multiple required
1563 tmp/foo.pyi:5: error: Name "f" already defined on line 2
1564 tmp/foo.pyi:5: error: Single overload definition, multiple required
1565
1566 [case testNonconsecutiveOverloadsMissingFirstOverload]
1567 from foo import *
1568 [file foo.pyi]
1569 from typing import overload
1570 def f(a: int) -> None: pass
1571 1
1572 @overload
1573 def f(a: str) -> None: pass
1574 [out]
1575 tmp/foo.pyi:4: error: Name "f" already defined on line 2
1576 tmp/foo.pyi:4: error: Single overload definition, multiple required
1577
1578 [case testNonconsecutiveOverloadsMissingLaterOverload]
1579 from foo import *
1580 [file foo.pyi]
1581 from typing import overload
1582 @overload
1583 def f(a: int) -> None: pass
1584 1
1585 def f(a: str) -> None: pass
1586 [out]
1587 tmp/foo.pyi:2: error: Single overload definition, multiple required
1588 tmp/foo.pyi:5: error: Name "f" already defined on line 2
1589
1590 [case testOverloadTuple]
1591 from foo import *
1592 [file foo.pyi]
1593 from typing import overload, Tuple
1594 @overload
1595 def f(x: int, y: Tuple[str, ...]) -> None: pass
1596 @overload
1597 def f(x: int, y: str) -> None: pass
1598 f(1, ('2', '3'))
1599 f(1, (2, '3')) # E: Argument 2 to "f" has incompatible type "tuple[int, str]"; expected "tuple[str, ...]"
1600 f(1, ('2',))
1601 f(1, '2')
1602 f(1, (2, 3)) # E: Argument 2 to "f" has incompatible type "tuple[int, int]"; expected "tuple[str, ...]"
1603 x = ('2', '3') # type: Tuple[str, ...]
1604 f(1, x)
1605 y = (2, 3) # type: Tuple[int, ...]
1606 f(1, y) # E: Argument 2 to "f" has incompatible type "tuple[int, ...]"; expected "tuple[str, ...]"
1607 [builtins fixtures/tuple.pyi]
1608
1609 [case testCallableSpecificOverload]
1610 from foo import *
1611 [file foo.pyi]
1612 from typing import overload, Callable
1613 @overload
1614 def f(a: Callable[[], int]) -> None: pass
1615 @overload
1616 def f(a: str) -> None: pass
1617 f(0) # E: No overload variant of "f" matches argument type "int" \
1618 # N: Possible overload variants: \
1619 # N: def f(a: Callable[[], int]) -> None \
1620 # N: def f(a: str) -> None
1621
1622 [case testCustomRedefinitionDecorator]
1623
1624 from typing import Any, Callable, Type
1625
1626 class Chain(object):
1627 def chain(self, function: Callable[[Any], int]) -> 'Chain':
1628 return self
1629
1630 class Test(object):
1631 do_chain = Chain()
1632
1633 @do_chain.chain # E: Name "do_chain" already defined on line 9
1634 def do_chain(self) -> int:
1635 return 2
1636
1637 @do_chain.chain # E: Name "do_chain" already defined on line 11
1638 def do_chain(self) -> int:
1639 return 3
1640
1641 t = Test()
1642 reveal_type(t.do_chain) # N: Revealed type is "__main__.Chain"
1643
1644 [case testOverloadWithOverlappingItemsAndAnyArgument1]
1645 from typing import overload, Any
1646
1647 @overload
1648 def f(x: int) -> int: ...
1649 @overload
1650 def f(x: object) -> object: ...
1651 def f(x): pass
1652
1653 a: Any
1654 reveal_type(f(a)) # N: Revealed type is "Any"
1655
1656 [case testOverloadWithOverlappingItemsAndAnyArgument2]
1657 from typing import overload, Any
1658
1659 @overload
1660 def f(x: int) -> int: ...
1661 @overload
1662 def f(x: float) -> float: ...
1663 def f(x): pass
1664
1665 a: Any
1666 reveal_type(f(a)) # N: Revealed type is "Any"
1667
1668 [case testOverloadWithOverlappingItemsAndAnyArgument3]
1669 from typing import overload, Any
1670
1671 @overload
1672 def f(x: int) -> int: ...
1673 @overload
1674 def f(x: str) -> str: ...
1675 def f(x): pass
1676
1677 a: Any
1678 reveal_type(f(a)) # N: Revealed type is "Any"
1679
1680 [case testOverloadWithOverlappingItemsAndAnyArgument4]
1681 from typing import overload, Any
1682
1683 @overload
1684 def f(x: int, y: int, z: str) -> int: ...
1685 @overload
1686 def f(x: object, y: int, z: str) -> object: ...
1687 def f(x): pass
1688
1689 a: Any
1690 # Any causes ambiguity
1691 reveal_type(f(a, 1, '')) # N: Revealed type is "Any"
1692 # Any causes no ambiguity
1693 reveal_type(f(1, a, a)) # N: Revealed type is "builtins.int"
1694 reveal_type(f('', a, a)) # N: Revealed type is "builtins.object"
1695 # Like above, but use keyword arguments.
1696 reveal_type(f(y=1, z='', x=a)) # N: Revealed type is "Any"
1697 reveal_type(f(y=a, z='', x=1)) # N: Revealed type is "builtins.int"
1698 reveal_type(f(z='', x=1, y=a)) # N: Revealed type is "builtins.int"
1699 reveal_type(f(z='', x=a, y=1)) # N: Revealed type is "Any"
1700
1701 [case testOverloadWithOverlappingItemsAndAnyArgument5]
1702 from typing import overload, Any, Union
1703
1704 class A: pass
1705 class B(A): pass
1706
1707 @overload
1708 def f(x: B) -> B: ...
1709 @overload
1710 def f(x: Union[A, B]) -> A: ...
1711 def f(x): pass
1712
1713 # Note: overloads ignore promotions so we treat 'int' and 'float' as distinct types
1714 @overload
1715 def g(x: int) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
1716 @overload
1717 def g(x: Union[int, float]) -> float: ...
1718 def g(x): pass
1719
1720 a: Any
1721 reveal_type(f(a)) # N: Revealed type is "Any"
1722 reveal_type(g(a)) # N: Revealed type is "Any"
1723
1724 [case testOverloadWithOverlappingItemsAndAnyArgument6]
1725 from typing import overload, Any
1726
1727 @overload
1728 def f(x: int, y: int) -> int: ...
1729 @overload
1730 def f(x: float, y: int, z: str) -> float: ...
1731 @overload
1732 def f(x: object, y: int, z: str, a: None) -> str: ...
1733 def f(x): pass
1734
1735 a: Any
1736 # Any causes ambiguity
1737 reveal_type(f(*a)) # N: Revealed type is "Any"
1738 reveal_type(f(a, *a)) # N: Revealed type is "Any"
1739 reveal_type(f(1, *a)) # N: Revealed type is "Any"
1740 reveal_type(f(1.1, *a)) # N: Revealed type is "Any"
1741 reveal_type(f('', *a)) # N: Revealed type is "builtins.str"
1742
1743 [case testOverloadWithOverlappingItemsAndAnyArgument7]
1744 from typing import overload, Any
1745
1746 @overload
1747 def f(x: int, y: int, z: int) -> int: ...
1748 @overload
1749 def f(x: object, y: int, z: int) -> object: ...
1750 def f(x): pass
1751
1752 @overload
1753 def g(x: int, y: int, z: int) -> int: ...
1754 @overload
1755 def g(x: object, y: int, z: str) -> object: ...
1756 def g(x): pass
1757
1758 a: Any
1759 reveal_type(f(1, *a)) # N: Revealed type is "builtins.int"
1760 reveal_type(g(1, *a)) # N: Revealed type is "Any"
1761
1762 [case testOverloadWithOverlappingItemsAndAnyArgument8]
1763 from typing import overload, Any
1764
1765 @overload
1766 def f(x: int, y: int, z: int) -> str: ...
1767 @overload
1768 def f(x: object, y: int, z: int) -> str: ...
1769 def f(x): pass
1770
1771 a: Any
1772 # The return type is not ambiguous so Any arguments cause no ambiguity.
1773 reveal_type(f(a, 1, 1)) # N: Revealed type is "builtins.str"
1774 reveal_type(f(1, *a)) # N: Revealed type is "builtins.str"
1775
1776 [case testOverloadWithOverlappingItemsAndAnyArgument9]
1777 from typing import overload, Any, List
1778
1779 @overload
1780 def f(x: List[int]) -> List[int]: ...
1781 @overload
1782 def f(x: List[Any]) -> List[Any]: ...
1783 def f(x): pass
1784
1785 a: Any
1786 b: List[Any]
1787 c: List[str]
1788 d: List[int]
1789 reveal_type(f(a)) # N: Revealed type is "builtins.list[Any]"
1790 reveal_type(f(b)) # N: Revealed type is "builtins.list[Any]"
1791 reveal_type(f(c)) # N: Revealed type is "builtins.list[Any]"
1792 reveal_type(f(d)) # N: Revealed type is "builtins.list[builtins.int]"
1793
1794 [builtins fixtures/list.pyi]
1795
1796 [case testOverloadWithOverlappingItemsAndAnyArgument10]
1797 from typing import overload, Any
1798
1799 @overload
1800 def f(*, x: int = 3, y: int = 3) -> int: ...
1801 @overload
1802 def f(**kwargs: str) -> str: ...
1803 def f(*args, **kwargs): pass
1804
1805 a: Any
1806 i: int
1807 reveal_type(f(x=a, y=i)) # N: Revealed type is "builtins.int"
1808 reveal_type(f(y=a)) # N: Revealed type is "Any"
1809 reveal_type(f(x=a, y=a)) # N: Revealed type is "Any"
1810
1811 [builtins fixtures/dict.pyi]
1812
1813 [case testOverloadWithOverlappingItemsAndAnyArgument11]
1814 from typing import overload, Any, Dict
1815
1816 @overload
1817 def f(x: int = 3, **kwargs: int) -> int: ...
1818 @overload
1819 def f(**kwargs: str) -> str: ...
1820 def f(*args, **kwargs): pass
1821
1822 a: Dict[str, Any]
1823 i: int
1824 reveal_type(f(x=i, **a)) # N: Revealed type is "builtins.int"
1825 reveal_type(f(**a)) # N: Revealed type is "Any"
1826
1827 [builtins fixtures/dict.pyi]
1828
1829 [case testOverloadWithOverlappingItemsAndAnyArgument12]
1830 from typing import overload, Any
1831
1832 @overload
1833 def f(x: int) -> Any: ...
1834 @overload
1835 def f(x: str) -> str: ...
1836 def f(x): pass
1837
1838 a: Any
1839 reveal_type(f(a)) # N: Revealed type is "Any"
1840
1841 [case testOverloadWithOverlappingItemsAndAnyArgument13]
1842 from typing import Any, overload, TypeVar, Generic
1843
1844 class slice: pass
1845
1846 T = TypeVar('T')
1847 class A(Generic[T]):
1848 @overload
1849 def f(self, x: int) -> T: ...
1850 @overload
1851 def f(self, x: slice) -> A[T]: ...
1852 def f(self, x): ...
1853
1854 i: Any
1855 a: A[Any]
1856 reveal_type(a.f(i)) # N: Revealed type is "Any"
1857
1858 [case testOverloadWithOverlappingItemsAndAnyArgument14]
1859 from typing import Any, overload, TypeVar, Generic
1860
1861 T = TypeVar('T')
1862
1863 class Wrapper(Generic[T]): pass
1864 class slice: pass
1865
1866 class A(Generic[T]):
1867 @overload
1868 def f(self, x: int) -> Wrapper[T]: ...
1869 @overload
1870 def f(self, x: slice) -> Wrapper[A[T]]: ...
1871 def f(self, x): ...
1872
1873 i: Any
1874 a: A[Any]
1875 reveal_type(a.f(i)) # N: Revealed type is "__main__.Wrapper[Any]"
1876
1877 [case testOverloadWithOverlappingItemsAndAnyArgument15]
1878 from typing import overload, Any, Union
1879
1880 @overload
1881 def f(x: int) -> str: ...
1882 @overload
1883 def f(x: str) -> str: ...
1884 def f(x): pass
1885
1886 @overload
1887 def g(x: int) -> Union[str, int]: ...
1888 @overload
1889 def g(x: str) -> Union[int, str]: ...
1890 def g(x): pass
1891
1892 a: Any
1893 reveal_type(f(a)) # N: Revealed type is "builtins.str"
1894 reveal_type(g(a)) # N: Revealed type is "builtins.str | builtins.int"
1895
1896 [case testOverloadWithOverlappingItemsAndAnyArgument16]
1897 from typing import overload, Any, Union, Callable
1898
1899 @overload
1900 def f(x: int) -> Callable[[int, int], int]: ...
1901 @overload
1902 def f(x: str) -> Callable[[str], str]: ...
1903 def f(x): pass
1904
1905 a: Any
1906 reveal_type(f(a)) # N: Revealed type is "def (*Any, **Any) -> Any"
1907 reveal_type(f(a)(a)) # N: Revealed type is "Any"
1908
1909 [case testOverloadOnOverloadWithType]
1910 from typing import Any, Type, TypeVar, overload
1911 from mod import MyInt
1912 T = TypeVar('T')
1913
1914 @overload
1915 def make(cls: Type[T]) -> T: pass
1916 @overload
1917 def make() -> Any: pass
1918
1919 def make(*args):
1920 pass
1921
1922 c = make(MyInt)
1923 reveal_type(c) # N: Revealed type is "mod.MyInt"
1924
1925 [file mod.pyi]
1926 from typing import overload
1927 class MyInt:
1928 @overload
1929 def __init__(self, x: str) -> None: pass
1930 @overload
1931 def __init__(self, x: str, y: int) -> None: pass
1932 [builtins fixtures/tuple.pyi]
1933 [out]
1934
1935 [case testOverloadTupleInstance]
1936 from typing import overload, Tuple, Any
1937
1938 class A: ...
1939 class A1(A): ...
1940 class B: ...
1941 class C: ...
1942 class D: ...
1943
1944 @overload
1945 def f(x: A) -> A: ...
1946 @overload
1947 def f(x: Tuple[C]) -> B: ...
1948 @overload
1949 def f(x: Tuple[A1, int]) -> C: ... # E: Overloaded function signatures 3 and 5 overlap with incompatible return types
1950 @overload
1951 def f(x: Tuple[A, str]) -> D: ...
1952 @overload
1953 def f(x: Tuple[A, int]) -> D: ...
1954 @overload
1955 def f(x: Tuple[()]) -> D: ...
1956 def f(x: Any) -> Any:...
1957 [builtins fixtures/tuple.pyi]
1958
1959 [case testOverloadTupleEllipsisNumargs]
1960 from typing import overload, Tuple, Any
1961
1962 class A: ...
1963 class B: ...
1964
1965 @overload
1966 def r1(x: Tuple[()]) -> B: ... # E: Overloaded function signatures 1 and 4 overlap with incompatible return types
1967 @overload
1968 def r1(x: Tuple[A]) -> B: ... # E: Overloaded function signatures 2 and 4 overlap with incompatible return types
1969 @overload
1970 def r1(x: Tuple[A, A]) -> B: ... # E: Overloaded function signatures 3 and 4 overlap with incompatible return types
1971 @overload
1972 def r1(x: Tuple[A, ...]) -> A: ...
1973 def r1(x: Any) -> Any: ...
1974
1975 @overload
1976 def r2(x: Tuple[A, ...]) -> A: ...
1977 @overload
1978 def r2(x: Tuple[A, A]) -> B: ... # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
1979 @overload
1980 def r2(x: Tuple[A]) -> B: ... # E: Overloaded function signature 3 will never be matched: signature 1's parameter type(s) are the same or broader
1981 @overload
1982 def r2(x: Tuple[()]) -> B: ... # E: Overloaded function signature 4 will never be matched: signature 1's parameter type(s) are the same or broader
1983 def r2(x: Any) -> Any: ...
1984
1985 [builtins fixtures/tuple.pyi]
1986
1987 [case testOverloadTupleEllipsisVariance]
1988 from typing import overload, Tuple, Any
1989
1990 class A: ...
1991 class A1(A): ...
1992 class B: ...
1993 class C: ...
1994 class D: ...
1995
1996 @overload
1997 def r(x: Tuple[A1, ...]) -> A: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
1998 @overload
1999 def r(x: Tuple[A, ...]) -> B: ...
2000 @overload
2001 def r(x: Tuple[B, ...]) -> C: ...
2002 def r(x: Any) -> Any:...
2003
2004 @overload
2005 def g(x: A) -> A: ...
2006 @overload
2007 def g(x: Tuple[A1, ...]) -> B: ... # E: Overloaded function signatures 2 and 3 overlap with incompatible return types
2008 @overload
2009 def g(x: Tuple[A, A]) -> C: ...
2010 @overload
2011 def g(x: Tuple[A, B]) -> D: ...
2012 def g(x: Any) -> Any:...
2013
2014 [builtins fixtures/tuple.pyi]
2015
2016 [case testOverloadWithMethodOverrideAndImplementation]
2017 from typing import overload, Union, Any
2018
2019 class Parent:
2020 @overload
2021 def f(self, arg: int) -> int: ...
2022 @overload
2023 def f(self, arg: str) -> str: ...
2024 def f(self, arg: Any) -> Any: ...
2025
2026 class Child1(Parent):
2027 @overload
2028 def f(self, arg: int) -> int: ...
2029 @overload
2030 def f(self, arg: str) -> str: ...
2031 def f(self, arg: Union[int, str]) -> Union[int, str]: ...
2032
2033 class Child2(Parent):
2034 @overload
2035 def f(self, arg: int) -> int: ...
2036 @overload
2037 def f(self, arg: str) -> str: ...
2038 def f(self, arg: Union[int, str]) -> int: ... # E: Overloaded function implementation cannot produce return type of signature 2
2039
2040 class Child3(Parent):
2041 @overload
2042 def f(self, arg: int) -> int: ...
2043 @overload
2044 def f(self, arg: str) -> str: ...
2045 def f(self, arg: Any) -> Any: ...
2046
2047 class Child4(Parent):
2048 @overload
2049 def f(self, arg: int) -> int: ...
2050 @overload
2051 def f(self, arg: str) -> str: ...
2052 def f(self, arg: Union[int, str]) -> Union[int, str]:
2053 return b'' # E: Incompatible return value type (got "bytes", expected "int | str")
2054
2055 [builtins fixtures/tuple.pyi]
2056
2057 [case testOverloadWithIncompatibleMethodOverrideAndImplementation]
2058 from typing import overload, Union, Any
2059
2060 class StrSub: pass
2061
2062 class ParentWithTypedImpl:
2063 @overload
2064 def f(self, arg: int) -> int: ...
2065 @overload
2066 def f(self, arg: str) -> str: ...
2067 def f(self, arg: Union[int, str]) -> Union[int, str]: ...
2068
2069 class Child1(ParentWithTypedImpl):
2070 @overload # Fail
2071 def f(self, arg: int) -> int: ...
2072 @overload
2073 def f(self, arg: StrSub) -> str: ...
2074 def f(self, arg: Union[int, StrSub]) -> Union[int, str]: ...
2075
2076 class Child2(ParentWithTypedImpl):
2077 @overload # Fail
2078 def f(self, arg: int) -> int: ...
2079 @overload
2080 def f(self, arg: StrSub) -> str: ...
2081 def f(self, arg: Any) -> Any: ...
2082
2083 class ParentWithDynamicImpl:
2084 @overload
2085 def f(self, arg: int) -> int: ...
2086 @overload
2087 def f(self, arg: str) -> str: ...
2088 def f(self, arg: Any) -> Any: ...
2089
2090 class Child3(ParentWithDynamicImpl):
2091 @overload # Fail
2092 def f(self, arg: int) -> int: ...
2093 @overload
2094 def f(self, arg: StrSub) -> str: ...
2095 def f(self, arg: Union[int, StrSub]) -> Union[int, str]: ...
2096
2097 class Child4(ParentWithDynamicImpl):
2098 @overload # Fail
2099 def f(self, arg: int) -> int: ...
2100 @overload
2101 def f(self, arg: StrSub) -> str: ...
2102 def f(self, arg: Any) -> Any: ...
2103
2104 [builtins fixtures/tuple.pyi]
2105 [out]
2106 main:13: error: Signature of "f" incompatible with supertype "ParentWithTypedImpl"
2107 main:13: note: Superclass:
2108 main:13: note: @overload
2109 main:13: note: def f(self, arg: int) -> int
2110 main:13: note: @overload
2111 main:13: note: def f(self, arg: str) -> str
2112 main:13: note: Subclass:
2113 main:13: note: @overload
2114 main:13: note: def f(self, arg: int) -> int
2115 main:13: note: @overload
2116 main:13: note: def f(self, arg: StrSub) -> str
2117 main:20: error: Signature of "f" incompatible with supertype "ParentWithTypedImpl"
2118 main:20: note: Superclass:
2119 main:20: note: @overload
2120 main:20: note: def f(self, arg: int) -> int
2121 main:20: note: @overload
2122 main:20: note: def f(self, arg: str) -> str
2123 main:20: note: Subclass:
2124 main:20: note: @overload
2125 main:20: note: def f(self, arg: int) -> int
2126 main:20: note: @overload
2127 main:20: note: def f(self, arg: StrSub) -> str
2128 main:34: error: Signature of "f" incompatible with supertype "ParentWithDynamicImpl"
2129 main:34: note: Superclass:
2130 main:34: note: @overload
2131 main:34: note: def f(self, arg: int) -> int
2132 main:34: note: @overload
2133 main:34: note: def f(self, arg: str) -> str
2134 main:34: note: Subclass:
2135 main:34: note: @overload
2136 main:34: note: def f(self, arg: int) -> int
2137 main:34: note: @overload
2138 main:34: note: def f(self, arg: StrSub) -> str
2139 main:41: error: Signature of "f" incompatible with supertype "ParentWithDynamicImpl"
2140 main:41: note: Superclass:
2141 main:41: note: @overload
2142 main:41: note: def f(self, arg: int) -> int
2143 main:41: note: @overload
2144 main:41: note: def f(self, arg: str) -> str
2145 main:41: note: Subclass:
2146 main:41: note: @overload
2147 main:41: note: def f(self, arg: int) -> int
2148 main:41: note: @overload
2149 main:41: note: def f(self, arg: StrSub) -> str
2150
2151 [case testOverloadAnyIsConsideredValidReturnSubtype]
2152 from typing import Any, overload, Optional
2153
2154 @overload
2155 def foo(x: None) -> Any: ...
2156 @overload
2157 def foo(x: Optional[str]) -> str: ...
2158 def foo(x): pass
2159
2160 @overload
2161 def bar(x: None) -> object: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
2162 @overload
2163 def bar(x: Optional[str]) -> str: ...
2164 def bar(x): pass
2165
2166 [case testOverloadWithNonPositionalArgs]
2167 from typing import overload
2168
2169 class A: ...
2170 class B: ...
2171 class C: ...
2172
2173 @overload
2174 def foo(*, p1: A, p2: B = B()) -> A: ...
2175 @overload
2176 def foo(*, p2: B = B()) -> B: ...
2177 def foo(p1, p2=None): ...
2178
2179 reveal_type(foo()) # N: Revealed type is "__main__.B"
2180 reveal_type(foo(p2=B())) # N: Revealed type is "__main__.B"
2181 reveal_type(foo(p1=A())) # N: Revealed type is "__main__.A"
2182
2183 [case testOverloadWithNonPositionalArgsIgnoresOrder]
2184 from typing import overload
2185
2186 class A: ...
2187 class B(A): ...
2188 class X: ...
2189 class Y: ...
2190
2191 @overload
2192 def f(*, p1: X, p2: A) -> X: ...
2193 @overload
2194 def f(*, p2: B, p1: X) -> Y: ... # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
2195 def f(*, p1, p2): ...
2196
2197 @overload
2198 def g(*, p1: X, p2: B) -> X: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
2199 @overload
2200 def g(*, p2: A, p1: X) -> Y: ...
2201 def g(*, p1, p2): ...
2202
2203 [case testOverloadWithVariableArgsAreOverlapping]
2204 from wrapper import *
2205 [file wrapper.pyi]
2206 from typing import overload
2207
2208 # Safety of this highly depends on the implementation, so we lean towards being silent.
2209 @overload
2210 def foo1(*x: int) -> int: ...
2211 @overload
2212 def foo1(x: int, y: int, z: int) -> str: ...
2213
2214 @overload
2215 def foo2(*x: int) -> int: ...
2216 @overload
2217 def foo2(x: int, y: str, z: int) -> str: ...
2218
2219 # Note: this is technically unsafe, but we don't report this for now.
2220 @overload
2221 def bar1(x: int, y: int, z: int) -> str: ...
2222 @overload
2223 def bar1(*x: int) -> int: ...
2224
2225 @overload
2226 def bar2(x: int, y: str, z: int) -> str: ...
2227 @overload
2228 def bar2(*x: int) -> int: ...
2229 [builtins fixtures/tuple.pyi]
2230
2231 [case testOverloadDetectsPossibleMatchesWithGenerics]
2232 # flags: --strict-optional
2233 from typing import overload, TypeVar, Generic, Optional, List
2234
2235 T = TypeVar('T')
2236 # The examples below are unsafe, but it is a quite common pattern
2237 # so we ignore the possibility of type variables taking value `None`
2238 # for the purpose of overload overlap checks.
2239
2240 @overload
2241 def foo(x: None, y: None) -> str: ...
2242 @overload
2243 def foo(x: T, y: T) -> int: ...
2244 def foo(x): ...
2245
2246 oi: Optional[int]
2247 reveal_type(foo(None, None)) # N: Revealed type is "builtins.str"
2248 reveal_type(foo(None, 42)) # N: Revealed type is "builtins.int"
2249 reveal_type(foo(42, 42)) # N: Revealed type is "builtins.int"
2250 reveal_type(foo(oi, None)) # N: Revealed type is "builtins.int | builtins.str"
2251 reveal_type(foo(oi, 42)) # N: Revealed type is "builtins.int"
2252 reveal_type(foo(oi, oi)) # N: Revealed type is "builtins.int | builtins.str"
2253
2254 @overload
2255 def foo_list(x: None) -> None: ...
2256 @overload
2257 def foo_list(x: T) -> List[T]: ...
2258 def foo_list(x): ...
2259
2260 reveal_type(foo_list(oi)) # N: Revealed type is "builtins.list[builtins.int] | None"
2261
2262 # What if 'T' is 'object'?
2263 @overload
2264 def bar(x: None, y: int) -> str: ...
2265 @overload
2266 def bar(x: T, y: T) -> int: ...
2267 def bar(x, y): ...
2268
2269 class Wrapper(Generic[T]):
2270 @overload
2271 def foo(self, x: None, y: None) -> str: ...
2272 @overload
2273 def foo(self, x: T, y: None) -> int: ...
2274 def foo(self, x): ...
2275
2276 @overload
2277 def bar(self, x: None, y: int) -> str: ...
2278 @overload
2279 def bar(self, x: T, y: T) -> int: ...
2280 def bar(self, x, y): ...
2281
2282 @overload
2283 def baz(x: str, y: str) -> str: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
2284 @overload
2285 def baz(x: T, y: T) -> int: ...
2286 def baz(x): ...
2287 [builtins fixtures/tuple.pyi]
2288
2289 [case testOverloadFlagsPossibleMatches]
2290 from wrapper import *
2291 [file wrapper.pyi]
2292 from typing import overload
2293
2294 @overload
2295 def foo1(x: str) -> str: ...
2296 @overload
2297 def foo1(x: str, y: str = ...) -> int: ...
2298
2299 @overload
2300 def foo2(x: str, y: str = ...) -> int: ...
2301 @overload
2302 def foo2(x: str) -> str: ... # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
2303
2304 @overload
2305 def foo3(x: str) -> str: ...
2306 @overload
2307 def foo3(x: str, y: str) -> int: ...
2308
2309 [case testOverloadPossibleOverlapWithArgsAndKwargs]
2310 from wrapper import *
2311 [file wrapper.pyi]
2312 from typing import overload
2313
2314 @overload
2315 def foo1(*args: int) -> int: ...
2316 @overload
2317 def foo1(**kwargs: int) -> str: ...
2318
2319 @overload
2320 def foo2(**kwargs: int) -> str: ...
2321 @overload
2322 def foo2(*args: int) -> int: ...
2323 [builtins fixtures/dict.pyi]
2324
2325 [case testOverloadPossibleOverlapWithVarargs]
2326 from wrapper import *
2327 [file wrapper.pyi]
2328 from typing import overload
2329
2330 @overload
2331 def foo1(*args: int) -> int: ...
2332 @overload
2333 def foo1(*args2: int) -> str: ... # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
2334
2335 @overload
2336 def foo2(*args: int) -> str: ...
2337 @overload
2338 def foo2(*args2: str) -> int: ...
2339
2340 @overload
2341 def foo3(*args: int) -> str: ...
2342 @overload
2343 def foo3(*args: str) -> int: ...
2344 [builtins fixtures/tuple.pyi]
2345
2346 [case testOverloadPossibleOverlapWithVarargs2]
2347 from wrapper import *
2348 [file wrapper.pyi]
2349 from typing import overload
2350
2351 @overload
2352 def foo1(*args: str) -> int: ...
2353 @overload
2354 def foo1(x: int, *args2: int) -> str: ...
2355
2356 @overload
2357 def foo2(x: int, *args: int) -> str: ...
2358 @overload
2359 def foo2(*args2: str) -> int: ...
2360
2361 # The two examples are unsafe, but this is hard to detect.
2362 @overload
2363 def foo3(*args: int) -> int: ...
2364 @overload
2365 def foo3(x: int, *args2: int) -> str: ...
2366
2367 @overload
2368 def foo4(x: int, *args: int) -> str: ...
2369 @overload
2370 def foo4(*args2: int) -> int: ...
2371 [builtins fixtures/tuple.pyi]
2372
2373 [case testOverloadPossibleOverlapWithVarargs3]
2374 from wrapper import *
2375 [file wrapper.pyi]
2376 from typing import overload
2377
2378 class Other: ...
2379
2380 @overload
2381 def foo1(x: Other, *args: int) -> str: ...
2382 @overload
2383 def foo1(*args: str) -> int: ...
2384
2385 @overload
2386 def foo2(*args: int) -> str: ...
2387 @overload
2388 def foo2(x: Other, *args: str) -> int: ...
2389
2390 @overload
2391 def foo3(x: Other = ..., *args: int) -> str: ...
2392 @overload
2393 def foo3(*args: str) -> int: ...
2394
2395 @overload
2396 def foo4(*args: int) -> str: ...
2397 @overload
2398 def foo4(x: Other = ..., *args: str) -> int: ...
2399 [builtins fixtures/tuple.pyi]
2400
2401 [case testOverloadPossibleOverlapWithVarargs4]
2402 from typing import overload
2403
2404 @overload
2405 def foo1(x: int = 0, y: int = 0) -> int: ...
2406 @overload
2407 def foo1(*xs: int) -> str: ...
2408 def foo1(*args): pass
2409
2410 @overload
2411 def foo2(*xs: int) -> str: ...
2412 @overload
2413 def foo2(x: int = 0, y: int = 0) -> int: ...
2414 def foo2(*args): pass
2415 [builtins fixtures/tuple.pyi]
2416
2417 [case testOverloadPossibleOverlapWithKwargs]
2418 from wrapper import *
2419 [file wrapper.pyi]
2420 from typing import overload
2421
2422 @overload
2423 def foo1(**kwargs: int) -> int: ...
2424 @overload
2425 def foo1(**kwargs2: int) -> str: ... # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
2426
2427 @overload
2428 def foo2(**kwargs: int) -> str: ...
2429 @overload
2430 def foo2(**kwargs2: str) -> int: ...
2431
2432 @overload
2433 def foo(**kwargs: int) -> str: ...
2434 @overload
2435 def foo(**kwargs: str) -> int: ...
2436 [builtins fixtures/dict.pyi]
2437
2438 [case testOverloadPossibleOverlapMixingNamedArgsWithVarargs]
2439 from wrapper import *
2440 [file wrapper.pyi]
2441 from typing import overload
2442
2443 @overload
2444 def foo1(x: str, *, y: str) -> str: ...
2445 @overload
2446 def foo1(*x: str) -> int: ...
2447
2448 @overload
2449 def foo2(*x: str) -> int: ...
2450 @overload
2451 def foo2(x: str, *, y: str) -> str: ...
2452 [builtins fixtures/tuple.pyi]
2453
2454 [case testOverloadPossibleOverlapMixingOptionalArgsWithVarargs]
2455 from wrapper import *
2456 [file wrapper.pyi]
2457 from typing import overload
2458
2459 @overload
2460 def foo1(x: str, y: str = ..., z: str = ...) -> str: ...
2461 @overload
2462 def foo1(*x: str) -> int: ...
2463
2464 @overload
2465 def foo2(*x: str) -> int: ...
2466 @overload
2467 def foo2(x: str, y: str = ..., z: str = ...) -> str: ...
2468
2469 @overload
2470 def foo3(x: int, y: str = ..., z: str = ...) -> str: ...
2471 @overload
2472 def foo3(*x: str) -> int: ...
2473 [builtins fixtures/tuple.pyi]
2474
2475 [case testOverloadPossibleOverlapMixingOptionalArgsWithVarargs2]
2476 from wrapper import *
2477 [file wrapper.pyi]
2478 from typing import overload
2479
2480 @overload
2481 def foo1(x: str, y: str = ..., z: int = ...) -> str: ...
2482 @overload
2483 def foo1(*x: str) -> int: ...
2484
2485 @overload
2486 def foo2(x: str, y: str = ..., z: int = ...) -> str: ...
2487 @overload
2488 def foo2(*x: str) -> int: ...
2489 [builtins fixtures/tuple.pyi]
2490
2491 [case testOverloadPossibleOverlapMixingNamedArgsWithKwargs]
2492 from wrapper import *
2493 [file wrapper.pyi]
2494 from typing import overload
2495
2496 @overload
2497 def foo1(*, x: str, y: str, z: str) -> str: ...
2498 @overload
2499 def foo1(**x: str) -> int: ...
2500
2501 @overload
2502 def foo2(**x: str) -> int: ...
2503 @overload
2504 def foo2(*, x: str, y: str, z: str) -> str: ... # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
2505
2506 @overload
2507 def foo3(*, x: int, y: str, z: str) -> str: ...
2508 @overload
2509 def foo3(*x: str) -> int: ...
2510
2511 [builtins fixtures/dict.pyi]
2512
2513 [case testOverloadPossibleOverlapMixingNamedArgsWithKwargs2]
2514 from wrapper import *
2515 [file wrapper.pyi]
2516 from typing import overload
2517
2518 @overload
2519 def foo1(*, x: str, y: str, z: int) -> str: ...
2520 @overload
2521 def foo1(**x: str) -> int: ...
2522
2523 @overload
2524 def foo2(**x: str) -> int: ...
2525 @overload
2526 def foo2(*, x: str, y: str, z: int) -> str: ...
2527
2528 @overload
2529 def foo3(*, x: str, y: str, z: int = ...) -> str: ...
2530 @overload
2531 def foo3(**x: str) -> int: ...
2532
2533 @overload
2534 def foo4(**x: str) -> int: ...
2535 @overload
2536 def foo4(*, x: str, y: str, z: int = ...) -> str: ...
2537 [builtins fixtures/dict.pyi]
2538
2539 [case testOverloadPossibleOverlapMixingNamedArgsWithKwargs3]
2540 from wrapper import *
2541 [file wrapper.pyi]
2542 from typing import overload
2543
2544 @overload
2545 def foo1(x: str, *, y: str, z: str) -> str: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types \
2546 # N: Flipping the order of overloads will fix this error
2547 @overload
2548 def foo1(**x: str) -> int: ...
2549
2550 @overload
2551 def foo2(**x: str) -> int: ...
2552 @overload
2553 def foo2(x: str, *, y: str, z: str) -> str: ...
2554
2555 [builtins fixtures/dict.pyi]
2556
2557 [case testOverloadVarargInputAndVarargDefinition]
2558 from typing import overload, List
2559
2560 class A: ...
2561 class B: ...
2562 class C: ...
2563
2564 @overload
2565 def foo(x: int) -> A: ...
2566 @overload
2567 def foo(x: int, y: int) -> B: ...
2568 @overload
2569 def foo(x: int, y: int, z: int, *args: int) -> C: ...
2570 def foo(*args): pass
2571
2572 reveal_type(foo(1)) # N: Revealed type is "__main__.A"
2573 reveal_type(foo(1, 2)) # N: Revealed type is "__main__.B"
2574 reveal_type(foo(1, 2, 3)) # N: Revealed type is "__main__.C"
2575
2576 reveal_type(foo(*[1])) # N: Revealed type is "__main__.C"
2577 reveal_type(foo(*[1, 2])) # N: Revealed type is "__main__.C"
2578 reveal_type(foo(*[1, 2, 3])) # N: Revealed type is "__main__.C"
2579
2580 x: List[int]
2581 reveal_type(foo(*x)) # N: Revealed type is "__main__.C"
2582
2583 y: List[str]
2584 foo(*y) # E: No overload variant of "foo" matches argument type "list[str]" \
2585 # N: Possible overload variants: \
2586 # N: def foo(x: int) -> A \
2587 # N: def foo(x: int, y: int) -> B \
2588 # N: def foo(x: int, y: int, z: int, *args: int) -> C
2589 [builtins fixtures/list.pyi]
2590
2591 [case testOverloadMultipleVarargDefinition]
2592 from typing import overload, List, Any
2593
2594 class A: ...
2595 class B: ...
2596 class C: ...
2597 class D: ...
2598
2599 @overload
2600 def foo(x: int) -> A: ...
2601 @overload
2602 def foo(x: int, y: int) -> B: ...
2603 @overload
2604 def foo(x: int, y: int, z: int, *args: int) -> C: ...
2605 @overload
2606 def foo(*x: str) -> D: ...
2607 def foo(*args): pass
2608
2609 reveal_type(foo(*[1, 2])) # N: Revealed type is "__main__.C"
2610 reveal_type(foo(*["a", "b"])) # N: Revealed type is "__main__.D"
2611
2612 x: List[Any]
2613 reveal_type(foo(*x)) # N: Revealed type is "Any"
2614 [builtins fixtures/list.pyi]
2615
2616 [case testOverloadMultipleVarargDefinitionComplex]
2617 from typing import TypeVar, overload, Any, Callable
2618
2619 T1 = TypeVar('T1')
2620 T2 = TypeVar('T2')
2621 T3 = TypeVar('T3')
2622
2623 @overload
2624 def chain_call(input_value: T1,
2625 f1: Callable[[T1], T2]) -> T2: ...
2626 @overload
2627 def chain_call(input_value: T1,
2628 f1: Callable[[T1], T2],
2629 f2: Callable[[T2], T3]) -> T3: ...
2630 @overload
2631 def chain_call(input_value: T1,
2632 *f_rest: Callable[[T1], T1]) -> T1: ...
2633 @overload
2634 def chain_call(input_value: T1,
2635 f1: Callable[[T1], T2],
2636 f2: Callable[[T2], T3],
2637 f3: Callable[[T3], Any],
2638 *f_rest: Callable[[Any], Any]) -> Any: ...
2639 def chain_call(input_value, *f_rest):
2640 for function in f_rest:
2641 input_value = function(input_value)
2642 return input_value
2643
2644
2645 class A: ...
2646 class B: ...
2647 class C: ...
2648 class D: ...
2649
2650 def f(x: A) -> A: ...
2651 def f1(x: A) -> B: ...
2652 def f2(x: B) -> C: ...
2653 def f3(x: C) -> D: ...
2654
2655 reveal_type(chain_call(A(), f1, f2)) # N: Revealed type is "__main__.C"
2656 reveal_type(chain_call(A(), f1, f2, f3)) # N: Revealed type is "Any"
2657 reveal_type(chain_call(A(), f, f, f, f)) # N: Revealed type is "__main__.A"
2658 [builtins fixtures/list.pyi]
2659
2660 [case testOverloadVarargsSelection]
2661 from typing import overload, Tuple
2662 @overload
2663 def f(x: int) -> Tuple[int]: ...
2664 @overload
2665 def f(x: int, y: int) -> Tuple[int, int]: ...
2666 @overload
2667 def f(*xs: int) -> Tuple[int, ...]: ...
2668 def f(*args): pass
2669
2670 i: int
2671 reveal_type(f(i)) # N: Revealed type is "tuple[builtins.int]"
2672 reveal_type(f(i, i)) # N: Revealed type is "tuple[builtins.int, builtins.int]"
2673 reveal_type(f(i, i, i)) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2674
2675 reveal_type(f(*[])) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2676 reveal_type(f(*[i])) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2677 reveal_type(f(*[i, i])) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2678 reveal_type(f(*[i, i, i])) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2679 [builtins fixtures/list.pyi]
2680
2681 [case testOverloadVarargsSelectionWithTuples]
2682 from typing import overload, Tuple
2683 @overload
2684 def f(x: int) -> Tuple[int]: ...
2685 @overload
2686 def f(x: int, y: int) -> Tuple[int, int]: ...
2687 @overload
2688 def f(*xs: int) -> Tuple[int, ...]: ...
2689 def f(*args): pass
2690
2691 i: int
2692 reveal_type(f(*())) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2693 reveal_type(f(*(i,))) # N: Revealed type is "tuple[builtins.int]"
2694 reveal_type(f(*(i, i))) # N: Revealed type is "tuple[builtins.int, builtins.int]"
2695 reveal_type(f(*(i, i, i))) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2696 [builtins fixtures/tuple.pyi]
2697
2698 [case testOverloadVarargsSelectionWithNamedTuples]
2699 from typing import overload, Tuple, NamedTuple
2700 @overload
2701 def f(x: int, y: int) -> Tuple[int, int]: ...
2702 @overload
2703 def f(*xs: int) -> Tuple[int, ...]: ...
2704 def f(*args): pass
2705
2706 A = NamedTuple('A', [('x', int), ('y', int)])
2707 B = NamedTuple('B', [('a', int), ('b', int)])
2708 C = NamedTuple('C', [('a', int), ('b', int), ('c', int)])
2709
2710 a: A
2711 b: B
2712 c: C
2713 reveal_type(f(*a)) # N: Revealed type is "tuple[builtins.int, builtins.int]"
2714 reveal_type(f(*b)) # N: Revealed type is "tuple[builtins.int, builtins.int]"
2715 reveal_type(f(*c)) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2716 [builtins fixtures/tuple.pyi]
2717
2718 [case testOverloadKwargsSelectionWithDict]
2719 from typing import overload, Tuple, Dict
2720 @overload
2721 def f(*, x: int) -> Tuple[int]: ...
2722 @overload
2723 def f(*, x: int, y: int) -> Tuple[int, int]: ...
2724 @overload
2725 def f(**xs: int) -> Tuple[int, ...]: ...
2726 def f(**kwargs): pass
2727
2728 empty: Dict[str, int]
2729 reveal_type(f(**empty)) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2730 reveal_type(f(**{'x': 4})) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2731 reveal_type(f(**{'x': 4, 'y': 4})) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2732 reveal_type(f(**{'a': 4, 'b': 4, 'c': 4})) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2733 [builtins fixtures/dict.pyi]
2734
2735 [case testOverloadKwargsSelectionWithTypedDict]
2736 from typing import overload, Tuple, TypedDict
2737 @overload
2738 def f(*, x: int) -> Tuple[int]: ...
2739 @overload
2740 def f(*, x: int, y: int) -> Tuple[int, int]: ...
2741 @overload
2742 def f(**xs: int) -> Tuple[int, ...]: ...
2743 def f(**args): pass
2744
2745 A = TypedDict('A', {'x': int})
2746 B = TypedDict('B', {'x': int, 'y': int})
2747 C = TypedDict('C', {'x': int, 'y': int, 'z': int})
2748
2749 a: A
2750 b: B
2751 c: C
2752
2753 reveal_type(f(**a)) # N: Revealed type is "tuple[builtins.int]"
2754 reveal_type(f(**b)) # N: Revealed type is "tuple[builtins.int, builtins.int]"
2755 reveal_type(f(**c)) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
2756 [builtins fixtures/dict.pyi]
2757 [typing fixtures/typing-typeddict.pyi]
2758
2759 [case testOverloadVarargsAndKwargsSelection]
2760 from typing import overload, Any, Tuple, Dict
2761
2762 class A: pass
2763 class B(A): pass
2764
2765 @overload
2766 def f(x: int, y: int) -> B: pass
2767 @overload
2768 def f(x: int, y: int, **kwargs: int) -> A: pass
2769 @overload
2770 def f(*args: int, **kwargs: int) -> Any: pass
2771 def f(*args, **kwargs): pass
2772
2773 a: Tuple[int, int]
2774 b: Tuple[int, ...]
2775 c: Dict[str, int]
2776
2777 reveal_type(f(*a, **c)) # N: Revealed type is "__main__.A"
2778 reveal_type(f(*b, **c)) # N: Revealed type is "__main__.A"
2779 reveal_type(f(*a)) # N: Revealed type is "__main__.B"
2780 reveal_type(f(*b)) # N: Revealed type is "Any"
2781
2782 # TODO: Should this be 'Any' instead?
2783 # The first matching overload with a kwarg is f(int, int, **int) -> A,
2784 # but f(*int, **int) -> Any feels like a better fit.
2785 reveal_type(f(**c)) # N: Revealed type is "__main__.A"
2786 [builtins fixtures/args.pyi]
2787
2788 [case testOverloadWithPartiallyOverlappingUnions]
2789 from typing import overload, Union
2790
2791 class A: ...
2792 class B: ...
2793 class C: ...
2794 class D: ...
2795
2796 @overload
2797 def f(x: Union[A, B]) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
2798 @overload
2799 def f(x: Union[B, C]) -> str: ...
2800 def f(x): ...
2801
2802 @overload
2803 def g(x: Union[A, B]) -> int: ...
2804 @overload
2805 def g(x: Union[B, C]) -> int: ...
2806 def g(x): ...
2807
2808 @overload
2809 def h(x: Union[A, B]) -> int: ...
2810 @overload
2811 def h(x: Union[C, D]) -> str: ...
2812 def h(x): ...
2813
2814 @overload
2815 def i(x: Union[A, B]) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
2816 @overload
2817 def i(x: Union[A, B, C]) -> str: ...
2818 def i(x): ...
2819
2820 [case testOverloadWithPartiallyOverlappingUnionsNested]
2821 from typing import overload, Union, List
2822
2823 class A: ...
2824 class B: ...
2825 class C: ...
2826 class D: ...
2827
2828 @overload
2829 def f(x: List[Union[A, B]]) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
2830 @overload
2831 def f(x: List[Union[B, C]]) -> str: ...
2832 def f(x): ...
2833
2834 @overload
2835 def g(x: List[Union[A, B]]) -> int: ...
2836 @overload
2837 def g(x: List[Union[B, C]]) -> int: ...
2838 def g(x): ...
2839
2840 @overload
2841 def h(x: List[Union[A, B]]) -> int: ...
2842 @overload
2843 def h(x: List[Union[C, D]]) -> str: ...
2844 def h(x): ...
2845
2846 @overload
2847 def i(x: List[Union[A, B]]) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types \
2848 # N: Flipping the order of overloads will fix this error
2849 @overload
2850 def i(x: List[Union[A, B, C]]) -> str: ...
2851 def i(x): ...
2852
2853 [builtins fixtures/list.pyi]
2854
2855 [case testOverloadPartialOverlapWithUnrestrictedTypeVar]
2856 from typing import TypeVar, overload
2857
2858 T = TypeVar('T')
2859
2860 # Note: this is unsafe, but it is hard to detect.
2861 @overload
2862 def f(x: int) -> str: ...
2863 @overload
2864 def f(x: T) -> T: ...
2865 def f(x): ...
2866
2867 @overload
2868 def g(x: int) -> int: ...
2869 @overload
2870 def g(x: T) -> T: ...
2871 def g(x): ...
2872
2873 [case testOverloadPartialOverlapWithUnrestrictedTypeVarNested]
2874 from typing import TypeVar, overload, List
2875
2876 T = TypeVar('T')
2877
2878 # Note: first two examples are unsafe, but it is hard to detect.
2879 @overload
2880 def f1(x: List[int]) -> str: ...
2881 @overload
2882 def f1(x: List[T]) -> T: ...
2883 def f1(x): ...
2884
2885 @overload
2886 def f2(x: List[int]) -> List[str]: ...
2887 @overload
2888 def f2(x: List[T]) -> List[T]: ...
2889 def f2(x): ...
2890
2891 @overload
2892 def g1(x: List[int]) -> int: ...
2893 @overload
2894 def g1(x: List[T]) -> T: ...
2895 def g1(x): ...
2896
2897 @overload
2898 def g2(x: List[int]) -> List[int]: ...
2899 @overload
2900 def g2(x: List[T]) -> List[T]: ...
2901 def g2(x): ...
2902
2903 [builtins fixtures/list.pyi]
2904
2905 [case testOverloadPartialOverlapWithUnrestrictedTypeVarInClass]
2906 from typing import TypeVar, overload, Generic
2907
2908 T = TypeVar('T')
2909
2910 class Wrapper(Generic[T]):
2911 # Similar to above: this is unsafe, but it is hard to detect.
2912 @overload
2913 def f(self, x: int) -> str: ...
2914 @overload
2915 def f(self, x: T) -> T: ...
2916 def f(self, x): ...
2917
2918 @overload
2919 def g(self, x: int) -> int: ...
2920 @overload
2921 def g(self, x: T) -> T: ...
2922 def g(self, x): ...
2923
2924 [case testOverloadPartialOverlapWithUnrestrictedTypeVarInClassNested]
2925 from typing import TypeVar, overload, Generic, List
2926
2927 T = TypeVar('T')
2928
2929 class Wrapper(Generic[T]):
2930 # Similar to above: first two examples are unsafe, but it is hard to detect.
2931 @overload
2932 def f1(self, x: List[int]) -> str: ...
2933 @overload
2934 def f1(self, x: List[T]) -> T: ...
2935 def f1(self, x): ...
2936
2937 @overload
2938 def f2(self, x: List[int]) -> List[str]: ...
2939 @overload
2940 def f2(self, x: List[T]) -> List[T]: ...
2941 def f2(self, x): ...
2942
2943 @overload
2944 def g1(self, x: List[int]) -> int: ...
2945 @overload
2946 def g1(self, x: List[T]) -> T: ...
2947 def g1(self, x): ...
2948
2949 @overload
2950 def g2(self, x: List[int]) -> List[int]: ...
2951 @overload
2952 def g2(self, x: List[T]) -> List[T]: ...
2953 def g2(self, x): ...
2954
2955 [builtins fixtures/list.pyi]
2956
2957 [case testOverloadTypedDictDifferentRequiredKeysMeansDictsAreDisjoint]
2958 from typing import TypedDict, overload
2959
2960 A = TypedDict('A', {'x': int, 'y': int})
2961 B = TypedDict('B', {'x': int, 'y': str})
2962
2963 @overload
2964 def f(x: A) -> int: ...
2965 @overload
2966 def f(x: B) -> str: ...
2967 def f(x): pass
2968 [builtins fixtures/dict.pyi]
2969 [typing fixtures/typing-typeddict.pyi]
2970
2971 [case testOverloadedTypedDictPartiallyOverlappingRequiredKeys]
2972 from typing import overload, TypedDict, Union
2973
2974 A = TypedDict('A', {'x': int, 'y': Union[int, str]})
2975 B = TypedDict('B', {'x': int, 'y': Union[str, float]})
2976
2977 @overload
2978 def f(x: A) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
2979 @overload
2980 def f(x: B) -> str: ...
2981 def f(x): pass
2982
2983 @overload
2984 def g(x: A) -> int: ...
2985 @overload
2986 def g(x: B) -> object: ...
2987 def g(x): pass
2988 [builtins fixtures/dict.pyi]
2989 [typing fixtures/typing-typeddict.pyi]
2990
2991 [case testOverloadedTypedDictFullyNonTotalDictsAreAlwaysPartiallyOverlapping]
2992 from typing import TypedDict, overload
2993
2994 A = TypedDict('A', {'x': int, 'y': str}, total=False)
2995 B = TypedDict('B', {'a': bool}, total=False)
2996 C = TypedDict('C', {'x': str, 'y': int}, total=False)
2997
2998 @overload
2999 def f(x: A) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
3000 @overload
3001 def f(x: B) -> str: ...
3002 def f(x): pass
3003
3004 @overload
3005 def g(x: A) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
3006 @overload
3007 def g(x: C) -> str: ...
3008 def g(x): pass
3009 [builtins fixtures/dict.pyi]
3010 [typing fixtures/typing-typeddict.pyi]
3011
3012 [case testOverloadedTotalAndNonTotalTypedDictsCanPartiallyOverlap]
3013 from typing import overload, TypedDict, Union
3014
3015 A = TypedDict('A', {'x': int, 'y': str})
3016 B = TypedDict('B', {'x': Union[int, str], 'y': str, 'z': int}, total=False)
3017
3018 @overload
3019 def f1(x: A) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
3020 @overload
3021 def f1(x: B) -> str: ...
3022 def f1(x): pass
3023
3024 @overload
3025 def f2(x: B) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
3026 @overload
3027 def f2(x: A) -> str: ...
3028 def f2(x): pass
3029
3030 [builtins fixtures/dict.pyi]
3031 [typing fixtures/typing-typeddict.pyi]
3032
3033 [case testOverloadedTypedDictsWithSomeOptionalKeysArePartiallyOverlapping]
3034 from typing import overload, TypedDict, Union
3035
3036 class A(TypedDict):
3037 x: int
3038 y: int
3039
3040 class B(TypedDict, total=False):
3041 z: str
3042
3043 class C(TypedDict, total=False):
3044 z: int
3045
3046 @overload
3047 def f(x: B) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
3048 @overload
3049 def f(x: C) -> str: ...
3050 def f(x): pass
3051
3052 [builtins fixtures/dict.pyi]
3053 [typing fixtures/typing-typeddict.pyi]
3054
3055 [case testOverloadedPartiallyOverlappingInheritedTypes1]
3056 from typing import overload, List, Union, TypeVar, Generic
3057
3058 class A: pass
3059 class B: pass
3060 class C: pass
3061
3062 T = TypeVar('T')
3063
3064 class ListSubclass(List[T]): pass
3065 class Unrelated(Generic[T]): pass
3066
3067 @overload
3068 def f(x: List[Union[A, B]]) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
3069 @overload
3070 def f(x: ListSubclass[Union[B, C]]) -> str: ...
3071 def f(x): pass
3072
3073 @overload
3074 def g(x: List[Union[A, B]]) -> int: ...
3075 @overload
3076 def g(x: Unrelated[Union[B, C]]) -> str: ...
3077 def g(x): pass
3078
3079 [builtins fixtures/list.pyi]
3080
3081 [case testOverloadedPartiallyOverlappingInheritedTypes2]
3082 from typing import overload, List, Union
3083
3084 class A: pass
3085 class B: pass
3086 class C: pass
3087
3088 class ListSubclass(List[Union[B, C]]): pass
3089
3090 @overload
3091 def f(x: List[Union[A, B]]) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
3092 @overload
3093 def f(x: ListSubclass) -> str: ...
3094 def f(x): pass
3095
3096 [builtins fixtures/list.pyi]
3097
3098 [case testOverloadedPartiallyOverlappingInheritedTypes3]
3099 from typing import overload, Union, Dict, TypeVar
3100
3101 class A: pass
3102 class B: pass
3103 class C: pass
3104
3105 S = TypeVar('S')
3106
3107 class DictSubclass(Dict[str, S]): pass
3108
3109 @overload
3110 def f(x: Dict[str, Union[A, B]]) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
3111 @overload
3112 def f(x: DictSubclass[Union[B, C]]) -> str: ...
3113 def f(x): pass
3114
3115 [builtins fixtures/dict.pyi]
3116
3117 [case testOverloadedPartiallyOverlappingTypeVarsAndUnion]
3118 from typing import overload, TypeVar, Union
3119
3120 class A: pass
3121 class B: pass
3122 class C: pass
3123
3124 S = TypeVar('S', A, B)
3125
3126 @overload
3127 def f(x: S) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types \
3128 # N: Flipping the order of overloads will fix this error
3129 @overload
3130 def f(x: Union[B, C]) -> str: ...
3131 def f(x): pass
3132
3133 @overload
3134 def g(x: Union[B, C]) -> int: ...
3135 @overload
3136 def g(x: S) -> str: ...
3137 def g(x): pass
3138
3139 [case testOverloadPartiallyOverlappingTypeVarsIdentical]
3140 from typing import overload, TypeVar, Union
3141
3142 T = TypeVar('T')
3143
3144 class A: pass
3145 class B: pass
3146 class C: pass
3147
3148 @overload
3149 def f(x: T, y: T, z: Union[A, B]) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
3150 @overload
3151 def f(x: T, y: T, z: Union[B, C]) -> str: ...
3152 def f(x, y, z): pass
3153
3154 [case testOverloadedPartiallyOverlappingCallables]
3155 from typing import overload, Union, Callable
3156
3157 class A: pass
3158 class B: pass
3159 class C: pass
3160
3161 @overload
3162 def f(x: Callable[[Union[A, B]], int]) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
3163 @overload
3164 def f(x: Callable[[Union[B, C]], int]) -> str: ...
3165 def f(x): pass
3166
3167 [case testOverloadNotConfusedForProperty]
3168 from typing import overload
3169
3170 class PropertyClass:
3171 @property
3172 def foo(self) -> str: return "..."
3173 @foo.setter
3174 def foo(self, value: str) -> None: pass
3175 @foo.deleter
3176 def foo(self) -> None: pass
3177
3178 class OverloadClass:
3179 @overload
3180 def foo(self) -> str: pass
3181 @overload
3182 def foo(self, value: str) -> None: pass
3183 @overload
3184 def foo(self) -> None: pass # E: Overloaded function signature 3 will never be matched: signature 1's parameter type(s) are the same or broader
3185 def foo(self, *args): pass
3186
3187 [builtins fixtures/property.pyi]
3188
3189 [case testOverloadInferUnionReturnBasic]
3190 from typing import overload, Union
3191
3192 class A: ...
3193 class B: ...
3194 class C: ...
3195 class D: ...
3196
3197 @overload
3198 def f1(x: A) -> B: ...
3199 @overload
3200 def f1(x: C) -> D: ...
3201 def f1(x): ...
3202
3203 arg1: Union[A, C]
3204 reveal_type(f1(arg1)) # N: Revealed type is "__main__.B | __main__.D"
3205
3206 arg2: Union[A, B]
3207 f1(arg2) # E: Argument 1 to "f1" has incompatible type "A | B"; expected "A"
3208
3209 @overload
3210 def f2(x: A) -> B: ...
3211 @overload
3212 def f2(x: C) -> B: ...
3213 def f2(x): ...
3214
3215 reveal_type(f2(arg1)) # N: Revealed type is "__main__.B"
3216
3217 [case testOverloadInferUnionReturnMultipleArguments]
3218 from typing import overload, Union
3219
3220 class A: ...
3221 class B: ...
3222 class C: ...
3223 class D: ...
3224
3225 @overload
3226 def f1(x: A, y: C) -> B: ...
3227 @overload
3228 def f1(x: C, y: A) -> D: ...
3229 def f1(x, y): ...
3230
3231 arg1: Union[A, C]
3232 reveal_type(f1(arg1, arg1))
3233
3234 @overload
3235 def f2(x: A, y: C) -> B: ...
3236 @overload
3237 def f2(x: C, y: C) -> D: ...
3238 def f2(x, y): ...
3239
3240 reveal_type(f2(arg1, arg1))
3241 reveal_type(f2(arg1, C()))
3242
3243 [out]
3244 main:15: note: Revealed type is "__main__.B"
3245 main:15: error: Argument 1 to "f1" has incompatible type "A | C"; expected "A"
3246 main:15: error: Argument 2 to "f1" has incompatible type "A | C"; expected "C"
3247 main:23: note: Revealed type is "__main__.B"
3248 main:23: error: Argument 1 to "f2" has incompatible type "A | C"; expected "A"
3249 main:23: error: Argument 2 to "f2" has incompatible type "A | C"; expected "C"
3250 main:24: note: Revealed type is "__main__.B | __main__.D"
3251
3252 [case testOverloadInferUnionRespectsVariance]
3253 from typing import overload, TypeVar, Union, Generic
3254
3255 class A: pass
3256 class B(A): pass
3257 class C(B): pass
3258
3259 T_co = TypeVar('T_co', covariant=True)
3260 T_contra = TypeVar('T_contra', contravariant=True)
3261
3262 class WrapperCo(Generic[T_co]): pass
3263 class WrapperContra(Generic[T_contra]): pass
3264
3265 @overload
3266 def foo(x: WrapperCo[B]) -> int: ...
3267 @overload
3268 def foo(x: WrapperContra[B]) -> str: ...
3269 def foo(x): pass
3270
3271 compat: Union[WrapperCo[C], WrapperContra[A]]
3272 reveal_type(foo(compat)) # N: Revealed type is "builtins.int | builtins.str"
3273
3274 not_compat: Union[WrapperCo[A], WrapperContra[C]]
3275 foo(not_compat) # E: Argument 1 to "foo" has incompatible type "WrapperCo[A] | WrapperContra[C]"; expected "WrapperCo[B]"
3276
3277 [case testOverloadInferUnionIfParameterNamesAreDifferent]
3278 from typing import overload, Union
3279
3280 class A: ...
3281 class B: ...
3282 class C: ...
3283
3284 @overload
3285 def f(x: A) -> B: ...
3286 @overload
3287 def f(y: B) -> C: ...
3288 def f(x): ...
3289
3290 x: Union[A, B]
3291 reveal_type(f(A())) # N: Revealed type is "__main__.B"
3292 reveal_type(f(B())) # N: Revealed type is "__main__.C"
3293 reveal_type(f(x)) # N: Revealed type is "__main__.B | __main__.C"
3294
3295 [case testOverloadInferUnionReturnFunctionsWithKwargs]
3296 from typing import overload, Union, Optional
3297
3298 class A: ...
3299 class B: ...
3300 class C: ...
3301 class D(B, C): ...
3302
3303 @overload
3304 def f(x: A) -> D: ...
3305 @overload
3306 def f(x: A, y: Optional[B] = None) -> C: ...
3307 @overload
3308 def f(x: A, z: Optional[C] = None) -> B: ...
3309 def f(x, y=None, z=None): ...
3310
3311 reveal_type(f(A(), B())) # N: Revealed type is "__main__.C"
3312 reveal_type(f(A(), C())) # N: Revealed type is "__main__.B"
3313
3314 arg: Union[B, C]
3315 reveal_type(f(A(), arg)) # N: Revealed type is "__main__.C | __main__.B"
3316 reveal_type(f(A())) # N: Revealed type is "__main__.D"
3317
3318 [builtins fixtures/tuple.pyi]
3319
3320 [case testOverloadInferUnionWithDifferingLengths]
3321 from typing import overload, Union
3322
3323 class Parent: ...
3324 class Child(Parent): ...
3325
3326 class A: ...
3327 class B: ...
3328
3329 @overload
3330 def f(x: A) -> Child: ...
3331 @overload
3332 def f(x: B, y: B = B()) -> Parent: ...
3333 def f(*args): ...
3334
3335 x: Union[A, B]
3336 reveal_type(f(x)) # N: Revealed type is "__main__.Parent"
3337 f(x, B()) # E: Argument 1 to "f" has incompatible type "A | B"; expected "B"
3338 [builtins fixtures/tuple.pyi]
3339
3340 [case testOverloadInferUnionWithMixOfPositionalAndOptionalArgs]
3341 from typing import overload, Union, Optional
3342
3343 class A: ...
3344 class B: ...
3345
3346 @overload
3347 def f(x: A) -> int: ...
3348 @overload
3349 def f(x: Optional[B] = None) -> str: ...
3350 def f(*args): ...
3351
3352 x: Union[A, B]
3353 y: Optional[A]
3354 z: Union[A, Optional[B]]
3355 reveal_type(f(x)) # N: Revealed type is "builtins.int | builtins.str"
3356 reveal_type(f(y)) # N: Revealed type is "builtins.int | builtins.str"
3357 reveal_type(f(z)) # N: Revealed type is "builtins.int | builtins.str"
3358 reveal_type(f()) # N: Revealed type is "builtins.str"
3359 [builtins fixtures/tuple.pyi]
3360
3361 [case testOverloadingInferUnionReturnWithTypevarWithValueRestriction]
3362 from typing import overload, Union, TypeVar, Generic
3363
3364 class A: pass
3365 class B: pass
3366 class C: pass
3367
3368 T = TypeVar('T', B, C)
3369
3370 class Wrapper(Generic[T]):
3371 @overload
3372 def f(self, x: T) -> B: ...
3373
3374 @overload
3375 def f(self, x: A) -> C: ...
3376
3377 def f(self, x): ...
3378
3379 obj: Wrapper[B] = Wrapper()
3380 x: Union[A, B]
3381
3382 reveal_type(obj.f(A())) # N: Revealed type is "__main__.C"
3383 reveal_type(obj.f(B())) # N: Revealed type is "__main__.B"
3384 reveal_type(obj.f(x)) # N: Revealed type is "__main__.C | __main__.B"
3385
3386 [case testOverloadingInferUnionReturnWithFunctionTypevarReturn]
3387 from typing import overload, Union, TypeVar, Generic
3388
3389 T = TypeVar('T')
3390
3391 class W1(Generic[T]): pass
3392 class W2(Generic[T]): pass
3393 class A: pass
3394 class B: pass
3395
3396 @overload
3397 def foo(x: W1[T]) -> T: ...
3398 @overload
3399 def foo(x: W2[T]) -> T: ...
3400 def foo(x): ...
3401
3402 def bar(x: Union[W1[T], W2[T]]) -> T: ...
3403
3404 def wrapper() -> None:
3405 obj1: Union[W1[A], W2[A]]
3406
3407 a1: A = foo(obj1)
3408 a2 = foo(obj1)
3409 reveal_type(a1) # N: Revealed type is "__main__.A"
3410 reveal_type(a2) # N: Revealed type is "__main__.A"
3411
3412 obj2: Union[W1[A], W2[B]]
3413
3414 reveal_type(foo(obj2)) # N: Revealed type is "__main__.A | __main__.B"
3415 bar(obj2) # E: Cannot infer value of type parameter "T" of "bar"
3416
3417 b1_overload: A = foo(obj2) # E: Incompatible types in assignment (expression has type "A | B", variable has type "A")
3418 b1_union: A = bar(obj2) # E: Cannot infer value of type parameter "T" of "bar"
3419
3420 [case testOverloadingInferUnionReturnWithObjectTypevarReturn]
3421 from typing import overload, Union, TypeVar, Generic
3422
3423 T = TypeVar('T')
3424
3425 class W1(Generic[T]): pass
3426 class W2(Generic[T]): pass
3427 class A: pass
3428 class B: pass
3429
3430 class SomeType(Generic[T]):
3431 @overload
3432 def foo(self, x: W1[T]) -> T: ...
3433 @overload
3434 def foo(self, x: W2[T]) -> T: ...
3435 def foo(self, x): ...
3436
3437 def bar(self, x: Union[W1[T], W2[T]]) -> T: ...
3438
3439 def wrapper() -> None:
3440 obj1: Union[W1[A], W2[A]]
3441
3442 a1 = SomeType[A]().foo(obj1)
3443 reveal_type(a1) # N: Revealed type is "__main__.A"
3444
3445 # Note: These should be fine, but mypy has an unrelated bug
3446 # that makes them error out?
3447 a2_overload: A = SomeType().foo(obj1) # E: Argument 1 to "foo" of "SomeType" has incompatible type "W1[A] | W2[A]"; expected "W1[Never]"
3448 a2_union: A = SomeType().bar(obj1) # E: Argument 1 to "bar" of "SomeType" has incompatible type "W1[A] | W2[A]"; expected "W1[Never] | W2[Never]"
3449
3450 SomeType().foo(obj1) # E: Argument 1 to "foo" of "SomeType" has incompatible type "W1[A] | W2[A]"; expected "W1[Never]"
3451 SomeType().bar(obj1) # E: Argument 1 to "bar" of "SomeType" has incompatible type "W1[A] | W2[A]"; expected "W1[Never] | W2[Never]"
3452
3453 [case testOverloadingInferUnionReturnWithBadObjectTypevarReturn]
3454 from typing import overload, Union, TypeVar, Generic
3455
3456 T = TypeVar('T')
3457
3458 class W1(Generic[T]): pass
3459 class W2(Generic[T]): pass
3460 class A: pass
3461 class B: pass
3462
3463 class SomeType(Generic[T]):
3464 @overload
3465 def foo(self, x: W1[T]) -> T: ...
3466 @overload
3467 def foo(self, x: W2[T]) -> T: ...
3468 def foo(self, x): ...
3469
3470 def bar(self, x: Union[W1[T], W2[T]]) -> T: ...
3471
3472 def wrapper(mysterious: T) -> T:
3473 obj1: Union[W1[A], W2[B]]
3474
3475 SomeType().foo(obj1) # E: Argument 1 to "foo" of "SomeType" has incompatible type "W1[A] | W2[B]"; expected "W1[Never]"
3476 SomeType().bar(obj1) # E: Argument 1 to "bar" of "SomeType" has incompatible type "W1[A] | W2[B]"; expected "W1[Never] | W2[Never]"
3477
3478 SomeType[A]().foo(obj1) # E: Argument 1 to "foo" of "SomeType" has incompatible type "W1[A] | W2[B]"; expected "W1[A]"
3479 SomeType[A]().bar(obj1) # E: Argument 1 to "bar" of "SomeType" has incompatible type "W1[A] | W2[B]"; expected "W1[A] | W2[A]"
3480
3481 SomeType[T]().foo(obj1) # E: Argument 1 to "foo" of "SomeType" has incompatible type "W1[A] | W2[B]"; expected "W1[T]"
3482 SomeType[T]().bar(obj1) # E: Argument 1 to "bar" of "SomeType" has incompatible type "W1[A] | W2[B]"; expected "W1[T] | W2[T]"
3483
3484 return mysterious
3485
3486 [case testOverloadingInferUnionReturnWithMixedTypevars]
3487 from typing import overload, Generic, TypeVar, List, Tuple, Union
3488
3489 class A: pass
3490 class B(A): pass
3491 class C(A): pass
3492
3493 T = TypeVar('T', bound=A)
3494 S = TypeVar('S')
3495
3496 class Dummy(Generic[T]):
3497 @overload
3498 def foo(self, x: List[Tuple[T, S]], y: S) -> T: ...
3499 @overload
3500 def foo(self, x: List[S], y: S) -> S: ...
3501 def foo(self, x: Union[List[Tuple[T, S]], List[S]], y: S) -> Union[T, S]: ...
3502
3503 T1 = TypeVar('T1', bound=A)
3504
3505 def t_is_same_bound(arg1: T1, arg2: S) -> Tuple[T1, S]:
3506 x1: Union[List[S], List[Tuple[T1, S]]]
3507 y1: S
3508 reveal_type(Dummy[T1]().foo(x1, y1)) # N: Revealed type is "S`-2 | T1`-1"
3509
3510 x2: Union[List[T1], List[Tuple[T1, T1]]]
3511 y2: T1
3512 reveal_type(Dummy[T1]().foo(x2, y2)) # N: Revealed type is "T1`-1"
3513
3514 return arg1, arg2
3515
3516 [builtins fixtures/list.pyi]
3517
3518 [case testOverloadingInferUnionReturnWithMixedTypevarsInnerMismatch]
3519 from typing import overload, Generic, TypeVar, List, Tuple, Union
3520
3521 class A: pass
3522 class B(A): pass
3523 class C(A): pass
3524
3525 T = TypeVar('T', bound=A)
3526 S = TypeVar('S')
3527
3528 class Dummy(Generic[T]):
3529 @overload
3530 def foo(self, x: List[Tuple[T, S]], y: S) -> T: ...
3531 @overload
3532 def foo(self, x: List[S], y: S) -> S: ...
3533 def foo(self, x: Union[List[Tuple[T, S]], List[S]], y: S) -> Union[T, S]: ...
3534
3535 T1 = TypeVar('T1', bound=A)
3536
3537 def t_is_same_bound(arg1: T1, arg2: S) -> Tuple[T1, S]:
3538 # The arguments in the tuple are swapped
3539 x3: Union[List[S], List[Tuple[S, T1]]]
3540 y3: S
3541 Dummy[T1]().foo(x3, y3) # E: Cannot infer value of type parameter "S" of "foo" of "Dummy" \
3542 # E: Argument 1 to "foo" of "Dummy" has incompatible type "list[S] | list[tuple[S, T1]]"; expected "list[tuple[T1, Any]]"
3543
3544 x4: Union[List[int], List[Tuple[C, int]]]
3545 y4: int
3546 reveal_type(Dummy[C]().foo(x4, y4)) # N: Revealed type is "builtins.int | __main__.C"
3547 Dummy[A]().foo(x4, y4) # E: Argument 1 to "foo" of "Dummy" has incompatible type "list[int] | list[tuple[C, int]]"; expected "list[tuple[A, int]]"
3548
3549 return arg1, arg2
3550
3551 [builtins fixtures/list.pyi]
3552
3553 [case testOverloadingInferUnionReturnWithMixedTypevarsTighterBound]
3554 from typing import overload, Generic, TypeVar, List, Tuple, Union
3555
3556 class A: pass
3557 class B(A): pass
3558 class C(A): pass
3559
3560 T = TypeVar('T', bound=A)
3561 S = TypeVar('S')
3562
3563 class Dummy(Generic[T]):
3564 @overload
3565 def foo(self, x: List[Tuple[T, S]], y: S) -> T: ...
3566 @overload
3567 def foo(self, x: List[S], y: S) -> S: ...
3568 def foo(self, x: Union[List[Tuple[T, S]], List[S]], y: S) -> Union[T, S]: ...
3569
3570 T1 = TypeVar('T1', bound=B)
3571
3572 def t_is_tighter_bound(arg1: T1, arg2: S) -> Tuple[T1, S]:
3573 x1: Union[List[S], List[Tuple[T1, S]]]
3574 y1: S
3575 reveal_type(Dummy[T1]().foo(x1, y1)) # N: Revealed type is "S`-2 | T1`-1"
3576
3577 x2: Union[List[T1], List[Tuple[T1, T1]]]
3578 y2: T1
3579 reveal_type(Dummy[T1]().foo(x2, y2)) # N: Revealed type is "T1`-1"
3580
3581 return arg1, arg2
3582
3583 [builtins fixtures/list.pyi]
3584
3585 [case testOverloadingInferUnionReturnWithTypevarsAndValueRestrictions]
3586 from typing import overload, Generic, TypeVar, List, Tuple, Union
3587
3588 class A: pass
3589 class B(A): pass
3590 class C(A): pass
3591
3592 T = TypeVar('T', bound=A)
3593 S = TypeVar('S')
3594
3595 class Dummy(Generic[T]):
3596 @overload
3597 def foo(self, x: List[Tuple[T, S]], y: S) -> T: ...
3598 @overload
3599 def foo(self, x: List[S], y: S) -> S: ...
3600 def foo(self, x: Union[List[Tuple[T, S]], List[S]], y: S) -> Union[T, S]: ...
3601
3602 T3 = TypeVar('T3', B, C)
3603
3604 def t_is_compatible_bound(arg1: T3, arg2: S) -> Tuple[T3, S]:
3605 x1: Union[List[S], List[Tuple[T3, S]]]
3606 y1: S
3607 reveal_type(Dummy[T3]().foo(x1, y1))
3608
3609 x2: Union[List[T3], List[Tuple[T3, T3]]]
3610 y2: T3
3611 reveal_type(Dummy[T3]().foo(x2, y2))
3612
3613 return arg1, arg2
3614
3615 [builtins fixtures/list.pyi]
3616 [out]
3617 main:22: note: Revealed type is "S`-2 | __main__.B"
3618 main:22: note: Revealed type is "S`-2 | __main__.C"
3619 main:26: note: Revealed type is "__main__.B"
3620 main:26: note: Revealed type is "__main__.C"
3621
3622 [case testOverloadInferUnionReturnWithInconsistentTypevarNames]
3623 from typing import overload, TypeVar, Union
3624
3625 T = TypeVar('T')
3626 S = TypeVar('S')
3627
3628 @overload
3629 def consistent(x: T, y: str) -> T: ...
3630 @overload
3631 def consistent(x: T, y: int) -> T: ...
3632 def consistent(x: T, y: Union[str, int]) -> T:
3633 return x
3634
3635 @overload
3636 def inconsistent(x: T, y: str) -> T: ...
3637 @overload
3638 def inconsistent(x: S, y: int) -> S: ...
3639 def inconsistent(x: T, y: Union[str, int]) -> T:
3640 return x
3641
3642 def test(x: T) -> T:
3643 y: Union[str, int]
3644
3645 reveal_type(consistent(x, y)) # N: Revealed type is "T`-1"
3646
3647 # On one hand, this overload is defined in a weird way; on the other, there's technically nothing wrong with it.
3648 inconsistent(x, y)
3649
3650 return x
3651
3652 [case testOverloadsAndNoneWithoutStrictOptional]
3653 # flags: --no-strict-optional
3654 from typing import overload, Optional
3655
3656 @overload
3657 def f(x: None) -> int: ...
3658 @overload
3659 def f(x: object) -> str: ...
3660 def f(x): ...
3661
3662 # We pretend strict-optional is enabled for overload definitions,
3663 # even in non-strict optional mode
3664 @overload
3665 def g(x: None) -> int: ...
3666 @overload
3667 def g(x: int) -> str: ...
3668 def g(x): ...
3669
3670 # Calls are still checked normally though
3671 a: None
3672 b: int
3673 c: Optional[int]
3674 reveal_type(g(a)) # N: Revealed type is "builtins.int"
3675 reveal_type(g(b)) # N: Revealed type is "builtins.str"
3676 reveal_type(g(c)) # N: Revealed type is "builtins.str"
3677
3678 [case testOverloadsAndNoneWithStrictOptional]
3679 from typing import overload, Optional
3680
3681 @overload
3682 def f(x: None) -> int: ...
3683 @overload
3684 def f(x: object) -> str: ...
3685 def f(x): ...
3686
3687 @overload
3688 def g(x: None) -> int: ...
3689 @overload
3690 def g(x: int) -> str: ...
3691 def g(x): ...
3692
3693 a: None
3694 b: int
3695 c: Optional[int]
3696 reveal_type(g(a)) # N: Revealed type is "builtins.int"
3697 reveal_type(g(b)) # N: Revealed type is "builtins.str"
3698 reveal_type(g(c)) # N: Revealed type is "builtins.str | builtins.int"
3699
3700 [case testOverloadsNoneAndTypeVarsWithNoStrictOptional]
3701 # flags: --no-strict-optional
3702 from typing import Callable, Iterable, TypeVar, overload, Optional
3703
3704 T = TypeVar('T')
3705 S = TypeVar('S')
3706
3707 @overload
3708 def mymap(func: None, seq: Iterable[T]) -> Iterable[T]: ...
3709 @overload
3710 def mymap(func: Callable[[T], S], seq: Iterable[T]) -> Iterable[S]: ...
3711 def mymap(*args): ...
3712
3713 seq = [1, 2, 3]
3714 f1: Callable[[int], str]
3715 f2: None
3716 f3: Optional[Callable[[int], str]]
3717
3718 reveal_type(mymap(f1, seq)) # N: Revealed type is "typing.Iterable[builtins.str]"
3719 reveal_type(mymap(f2, seq)) # N: Revealed type is "typing.Iterable[builtins.int]"
3720 reveal_type(mymap(f3, seq)) # N: Revealed type is "typing.Iterable[builtins.str]"
3721
3722 [builtins fixtures/list.pyi]
3723 [typing fixtures/typing-medium.pyi]
3724
3725 [case testOverloadsNoneAndTypeVarsWithStrictOptional]
3726 from typing import Callable, Iterable, TypeVar, overload, Optional
3727
3728 T = TypeVar('T')
3729 S = TypeVar('S')
3730
3731 @overload
3732 def mymap(func: None, seq: Iterable[T]) -> Iterable[T]: ...
3733 @overload
3734 def mymap(func: Callable[[T], S], seq: Iterable[T]) -> Iterable[S]: ...
3735 def mymap(*args): ...
3736
3737 seq = [1, 2, 3]
3738 f1: Callable[[int], str]
3739 f2: None
3740 f3: Optional[Callable[[int], str]]
3741
3742 reveal_type(mymap(f1, seq)) # N: Revealed type is "typing.Iterable[builtins.str]"
3743 reveal_type(mymap(f2, seq)) # N: Revealed type is "typing.Iterable[builtins.int]"
3744 reveal_type(mymap(f3, seq)) # N: Revealed type is "typing.Iterable[builtins.str] | typing.Iterable[builtins.int]"
3745
3746 [builtins fixtures/list.pyi]
3747 [typing fixtures/typing-medium.pyi]
3748
3749 [case testOverloadsAndNoReturnNarrowTypeNoStrictOptional1]
3750 # flags: --no-strict-optional
3751 from typing import overload, Union, NoReturn
3752
3753 @overload
3754 def narrow_int(x: str) -> NoReturn: ...
3755 @overload
3756 def narrow_int(x: int) -> int: ...
3757 def narrow_int(x: Union[int, str]) -> Union[int, NoReturn]:
3758 assert isinstance(x, int)
3759 return x
3760
3761 def test_narrow_int() -> None:
3762 a: Union[int, str]
3763 if int():
3764 a = narrow_int(a)
3765 reveal_type(a) # N: Revealed type is "builtins.int"
3766
3767 b: int
3768 if int():
3769 b = narrow_int(b)
3770 reveal_type(b) # N: Revealed type is "builtins.int"
3771
3772 c: str
3773 if int():
3774 c = narrow_int(c)
3775 reveal_type(c) # Note: branch is now dead, so no type is revealed
3776 # TODO: maybe we should make mypy report a warning instead?
3777
3778 [builtins fixtures/isinstance.pyi]
3779 [typing fixtures/typing-medium.pyi]
3780
3781 [case testOverloadsAndNoReturnNarrowTypeWithStrictOptional1]
3782 from typing import overload, Union, NoReturn
3783
3784 @overload
3785 def narrow_int(x: str) -> NoReturn: ...
3786 @overload
3787 def narrow_int(x: int) -> int: ...
3788 def narrow_int(x: Union[int, str]) -> Union[int, NoReturn]:
3789 assert isinstance(x, int)
3790 return x
3791
3792 def test_narrow_int() -> None:
3793 a: Union[int, str]
3794 if int():
3795 a = narrow_int(a)
3796 reveal_type(a) # N: Revealed type is "builtins.int"
3797
3798 b: int
3799 if int():
3800 b = narrow_int(b)
3801 reveal_type(b) # N: Revealed type is "builtins.int"
3802
3803 c: str
3804 if int():
3805 c = narrow_int(c)
3806 reveal_type(c) # Note: branch is now dead, so no type is revealed
3807 # TODO: maybe we should make mypy report a warning instead?
3808
3809 [builtins fixtures/isinstance.pyi]
3810 [typing fixtures/typing-medium.pyi]
3811
3812 [case testOverloadsAndNoReturnNarrowTypeNoStrictOptional2]
3813 # flags: --no-strict-optional
3814 from typing import overload, Union, TypeVar, NoReturn, Optional
3815
3816 T = TypeVar('T')
3817 @overload
3818 def narrow_none(x: None) -> NoReturn: ...
3819 @overload
3820 def narrow_none(x: T) -> T: ...
3821 def narrow_none(x: Optional[T]) -> Union[NoReturn, T]:
3822 assert x is not None
3823 return x
3824
3825 def test_narrow_none() -> None:
3826 a: Optional[int]
3827 if int():
3828 a = narrow_none(a)
3829 reveal_type(a) # N: Revealed type is "builtins.int"
3830
3831 b: int
3832 if int():
3833 b = narrow_none(b)
3834 reveal_type(b) # N: Revealed type is "builtins.int"
3835
3836 c: None
3837 if int():
3838 c = narrow_none(c)
3839 reveal_type(c) # Note: branch is now dead, so no type is revealed
3840
3841 [builtins fixtures/isinstance.pyi]
3842 [typing fixtures/typing-medium.pyi]
3843
3844 [case testOverloadsAndNoReturnNarrowTypeWithStrictOptional2]
3845 from typing import overload, Union, TypeVar, NoReturn, Optional
3846
3847 T = TypeVar('T')
3848 @overload
3849 def narrow_none(x: None) -> NoReturn: ...
3850 @overload
3851 def narrow_none(x: T) -> T: ...
3852 def narrow_none(x: Optional[T]) -> Union[NoReturn, T]:
3853 assert x is not None
3854 return x
3855
3856 def test_narrow_none() -> None:
3857 a: Optional[int]
3858 if int():
3859 a = narrow_none(a)
3860 reveal_type(a) # N: Revealed type is "builtins.int"
3861
3862 b: int
3863 if int():
3864 b = narrow_none(b)
3865 reveal_type(b) # N: Revealed type is "builtins.int"
3866
3867 c: None
3868 if int():
3869 c = narrow_none(c)
3870 reveal_type(c) # Branch is now dead
3871
3872 [builtins fixtures/isinstance.pyi]
3873 [typing fixtures/typing-medium.pyi]
3874
3875
3876 [case testOverloadsAndNoReturnNarrowTypeNoStrictOptional3]
3877 # flags: --no-strict-optional
3878 from typing import overload, TypeVar, NoReturn, Optional
3879
3880 @overload
3881 def narrow_none_v2(x: None) -> NoReturn: ...
3882 @overload
3883 def narrow_none_v2(x: T) -> T: ...
3884 def narrow_none_v2(x: Optional[T]) -> T:
3885 assert x is not None
3886 return x
3887
3888 def test_narrow_none_v2() -> None:
3889 a: Optional[int]
3890 if int():
3891 a = narrow_none_v2(a)
3892 reveal_type(a) # N: Revealed type is "builtins.int"
3893
3894 b: int
3895 if int():
3896 b = narrow_none_v2(b)
3897 reveal_type(b) # N: Revealed type is "builtins.int"
3898
3899 c: None
3900 if int():
3901 c = narrow_none_v2(c)
3902 reveal_type(c) # Note: branch is now dead, so no type is revealed
3903
3904 [builtins fixtures/isinstance.pyi]
3905 [typing fixtures/typing-medium.pyi]
3906
3907 [case testOverloadsAndNoReturnNarrowTypeWithStrictOptional3]
3908 from typing import overload, TypeVar, NoReturn, Optional
3909
3910 @overload
3911 def narrow_none_v2(x: None) -> NoReturn: ...
3912 @overload
3913 def narrow_none_v2(x: T) -> T: ...
3914 def narrow_none_v2(x: Optional[T]) -> T:
3915 assert x is not None
3916 return x
3917
3918 def test_narrow_none_v2() -> None:
3919 a: Optional[int]
3920 if int():
3921 a = narrow_none_v2(a)
3922 reveal_type(a) # N: Revealed type is "builtins.int"
3923
3924 b: int
3925 if int():
3926 b = narrow_none_v2(b)
3927 reveal_type(b) # N: Revealed type is "builtins.int"
3928
3929 c: None
3930 if int():
3931 c = narrow_none_v2(c)
3932 reveal_type(c) # Note: branch is now dead, so no type is revealed
3933
3934 [builtins fixtures/isinstance.pyi]
3935 [typing fixtures/typing-medium.pyi]
3936
3937 [case testOverloadsAndNoReturnNarrowWhenBlacklistingSubtype]
3938 from typing import TypeVar, NoReturn, Union, overload
3939
3940 class Parent: ...
3941 class A(Parent): ...
3942 class B(Parent): ...
3943 T = TypeVar('T', bound=Parent)
3944
3945 @overload
3946 def narrow_to_not_a(x: A) -> NoReturn: ...
3947 @overload
3948 def narrow_to_not_a(x: T) -> T: ...
3949 def narrow_to_not_a(x: T) -> Union[NoReturn, T]:
3950 assert not isinstance(x, A)
3951 return x
3952
3953 def test() -> None:
3954 val: Union[A, B]
3955 if int():
3956 val = narrow_to_not_a(val)
3957 reveal_type(val) # N: Revealed type is "__main__.B"
3958
3959 val2: A
3960 if int():
3961 val2 = narrow_to_not_a(val2)
3962 reveal_type(val2) # Branch now dead
3963
3964 [builtins fixtures/isinstance.pyi]
3965 [typing fixtures/typing-medium.pyi]
3966
3967 [case testOverloadsAndNoReturnNarrowWhenBlacklistingSubtype2]
3968 from typing import TypeVar, NoReturn, Union, overload
3969
3970 class Parent: ...
3971 class A(Parent): ...
3972 class B(Parent): ...
3973 T = TypeVar('T', bound=Parent)
3974
3975 @overload
3976 def narrow_to_not_a_v2(x: A) -> NoReturn: ...
3977 @overload
3978 def narrow_to_not_a_v2(x: T) -> T: ...
3979 def narrow_to_not_a_v2(x: T) -> T:
3980 assert not isinstance(x, A)
3981 return x
3982
3983 def test_v2(val: Union[A, B], val2: A) -> None:
3984 if int():
3985 val = narrow_to_not_a_v2(val)
3986 reveal_type(val) # N: Revealed type is "__main__.B"
3987
3988 if int():
3989 val2 = narrow_to_not_a_v2(val2)
3990 reveal_type(val2) # Branch now dead
3991
3992 [builtins fixtures/isinstance.pyi]
3993 [typing fixtures/typing-medium.pyi]
3994
3995 [case testOverloadWithNonGenericDescriptor]
3996 from typing import overload, Any, Optional, Union
3997
3998 class NumberAttribute:
3999 @overload
4000 def __get__(self, instance: None, owner: Any) -> 'NumberAttribute': ...
4001 @overload
4002 def __get__(self, instance: object, owner: Any) -> int: ...
4003 def __get__(self, instance: Optional[object], owner: Any) -> Union['NumberAttribute', int]:
4004 if instance is None:
4005 return self
4006 else:
4007 return 3
4008
4009 def foo(self) -> str: ...
4010
4011 class MyModel:
4012 my_number = NumberAttribute()
4013
4014 reveal_type(MyModel().my_number) # N: Revealed type is "builtins.int"
4015 MyModel().my_number.foo() # E: "int" has no attribute "foo"
4016
4017 reveal_type(MyModel.my_number) # N: Revealed type is "__main__.NumberAttribute"
4018 reveal_type(MyModel.my_number.foo()) # N: Revealed type is "builtins.str"
4019
4020 [builtins fixtures/isinstance.pyi]
4021 [typing fixtures/typing-medium.pyi]
4022
4023 [case testOverloadWithNonGenericDescriptorLookalike]
4024 from typing import overload, Any, Optional, Union
4025
4026 class FakeAttribute:
4027 @overload
4028 def dummy(self, instance: None, owner: Any) -> 'FakeAttribute': ...
4029 @overload
4030 def dummy(self, instance: object, owner: Any) -> int: ...
4031 def dummy(self, instance: Optional[object], owner: Any) -> Union['FakeAttribute', int]: ...
4032
4033 [case testOverloadWithGenericDescriptor]
4034 from typing import overload, Any, Optional, TypeVar, Type, Union, Generic
4035
4036 T = TypeVar('T')
4037
4038 class NumberAttribute(Generic[T]):
4039 @overload
4040 def __get__(self, instance: None, owner: Type[T]) -> 'NumberAttribute[T]': ...
4041 @overload
4042 def __get__(self, instance: T, owner: Type[T]) -> int: ...
4043 def __get__(self, instance: Optional[T], owner: Type[T]) -> Union['NumberAttribute[T]', int]:
4044 if instance is None:
4045 return self
4046 else:
4047 return 3
4048
4049 def foo(self) -> str: ...
4050
4051 class MyModel:
4052 my_number = NumberAttribute[MyModel]()
4053
4054 reveal_type(MyModel().my_number) # N: Revealed type is "builtins.int"
4055 MyModel().my_number.foo() # E: "int" has no attribute "foo"
4056
4057 reveal_type(MyModel.my_number) # N: Revealed type is "__main__.NumberAttribute[__main__.MyModel]"
4058 reveal_type(MyModel.my_number.foo()) # N: Revealed type is "builtins.str"
4059
4060 reveal_type(NumberAttribute[MyModel]().__get__(None, MyModel)) # N: Revealed type is "__main__.NumberAttribute[__main__.MyModel]"
4061 reveal_type(NumberAttribute[str]().__get__(None, str)) # N: Revealed type is "__main__.NumberAttribute[builtins.str]"
4062
4063 [builtins fixtures/isinstance.pyi]
4064 [typing fixtures/typing-medium.pyi]
4065
4066 [case testOverloadWithGenericDescriptorLookalike]
4067 from typing import overload, Any, Optional, TypeVar, Type, Union, Generic
4068
4069 T = TypeVar('T')
4070
4071 class FakeAttribute(Generic[T]):
4072 @overload
4073 def dummy(self, instance: None, owner: Type[T]) -> 'FakeAttribute[T]': ...
4074 @overload
4075 def dummy(self, instance: T, owner: Type[T]) -> int: ...
4076 def dummy(self, instance: Optional[T], owner: Type[T]) -> Union['FakeAttribute[T]', int]: ...
4077
4078 [case testOverloadWithClassMethods]
4079 from typing import overload
4080
4081 class Wrapper:
4082 @overload
4083 @classmethod
4084 def foo(cls, x: int) -> int: ...
4085 @overload
4086 @classmethod
4087 def foo(cls, x: str) -> str: ...
4088 @classmethod
4089 def foo(cls, x): pass
4090
4091 reveal_type(Wrapper.foo(3)) # N: Revealed type is "builtins.int"
4092 reveal_type(Wrapper.foo("foo")) # N: Revealed type is "builtins.str"
4093
4094 [builtins fixtures/classmethod.pyi]
4095
4096 [case testOverloadWithInconsistentClassMethods]
4097 from typing import overload
4098
4099 class Wrapper1:
4100 @overload # E: Overload does not consistently use the "@classmethod" decorator on all function signatures.
4101 @classmethod
4102 def foo(cls, x: int) -> int: ...
4103 @overload
4104 @classmethod
4105 def foo(cls, x: str) -> str: ...
4106 def foo(cls, x): pass
4107
4108 class Wrapper2:
4109 @overload # E: Overload does not consistently use the "@classmethod" decorator on all function signatures.
4110 @classmethod
4111 def foo(cls, x: int) -> int: ...
4112 @overload
4113 def foo(cls, x: str) -> str: ...
4114 @classmethod
4115 def foo(cls, x): pass
4116
4117 class Wrapper3:
4118 @overload # E: Overload does not consistently use the "@classmethod" decorator on all function signatures.
4119 def foo(cls, x: int) -> int: ...
4120 @overload
4121 def foo(cls, x: str) -> str: ...
4122 @classmethod
4123 def foo(cls, x): pass
4124
4125 [builtins fixtures/classmethod.pyi]
4126
4127 [case testOverloadWithSwappedDecorators]
4128 from typing import overload
4129
4130 class Wrapper1:
4131 @classmethod
4132 @overload
4133 def foo(cls, x: int) -> int: ...
4134
4135 @classmethod
4136 @overload
4137 def foo(cls, x: str) -> str: ...
4138
4139 @classmethod
4140 def foo(cls, x): pass
4141
4142 class Wrapper2:
4143 @classmethod
4144 @overload
4145 def foo(cls, x: int) -> int: ...
4146
4147 @overload
4148 @classmethod
4149 def foo(cls, x: str) -> str: ...
4150
4151 @classmethod
4152 def foo(cls, x): pass
4153
4154 class Wrapper3:
4155 @classmethod # E: Overload does not consistently use the "@classmethod" decorator on all function signatures.
4156 @overload
4157 def foo(cls, x: int) -> int: ...
4158
4159 @overload
4160 def foo(cls, x: str) -> str: ...
4161
4162 def foo(cls, x): pass
4163
4164 reveal_type(Wrapper1.foo(3)) # N: Revealed type is "builtins.int"
4165 reveal_type(Wrapper2.foo(3)) # N: Revealed type is "builtins.int"
4166
4167 [builtins fixtures/classmethod.pyi]
4168
4169 [case testOverloadFaultyClassMethodInheritance]
4170 from typing import overload
4171
4172 class A: pass
4173 class B(A): pass
4174 class C(B): pass
4175
4176 class Parent:
4177 @overload
4178 @classmethod
4179 def foo(cls, x: B) -> int: ...
4180
4181 @overload
4182 @classmethod
4183 def foo(cls, x: str) -> str: ...
4184
4185 @classmethod
4186 def foo(cls, x): pass
4187
4188 class BadChild(Parent):
4189 @overload # Fail
4190 @classmethod
4191 def foo(cls, x: C) -> int: ...
4192
4193 @overload
4194 @classmethod
4195 def foo(cls, x: str) -> str: ...
4196
4197 @classmethod
4198 def foo(cls, x): pass
4199
4200 class GoodChild(Parent):
4201 @overload
4202 @classmethod
4203 def foo(cls, x: A) -> int: ...
4204
4205 @overload
4206 @classmethod
4207 def foo(cls, x: str) -> str: ...
4208
4209 @classmethod
4210 def foo(cls, x): pass
4211
4212 [builtins fixtures/classmethod.pyi]
4213 [out]
4214 main:20: error: Signature of "foo" incompatible with supertype "Parent"
4215 main:20: note: Superclass:
4216 main:20: note: @overload
4217 main:20: note: @classmethod
4218 main:20: note: def foo(cls, x: B) -> int
4219 main:20: note: @overload
4220 main:20: note: @classmethod
4221 main:20: note: def foo(cls, x: str) -> str
4222 main:20: note: Subclass:
4223 main:20: note: @overload
4224 main:20: note: @classmethod
4225 main:20: note: def foo(cls, x: C) -> int
4226 main:20: note: @overload
4227 main:20: note: @classmethod
4228 main:20: note: def foo(cls, x: str) -> str
4229
4230 [case testOverloadClassMethodMixingInheritance]
4231 from typing import overload
4232
4233 class BadParent:
4234 @overload
4235 @classmethod
4236 def foo(cls, x: int) -> int: ...
4237
4238 @overload
4239 @classmethod
4240 def foo(cls, x: str) -> str: ...
4241
4242 @classmethod
4243 def foo(cls, x): pass
4244
4245 class BadChild(BadParent):
4246 @overload # Fail
4247 def foo(cls, x: int) -> int: ...
4248
4249 @overload
4250 def foo(cls, x: str) -> str: ...
4251
4252 def foo(cls, x): pass
4253
4254 class GoodParent:
4255 @overload
4256 def foo(cls, x: int) -> int: ...
4257
4258 @overload
4259 def foo(cls, x: str) -> str: ...
4260
4261 def foo(cls, x): pass
4262
4263 class GoodChild(GoodParent):
4264 @overload
4265 @classmethod
4266 def foo(cls, x: int) -> int: ...
4267
4268 @overload
4269 @classmethod
4270 def foo(cls, x: str) -> str: ...
4271
4272 @classmethod
4273 def foo(cls, x): pass
4274
4275 [builtins fixtures/classmethod.pyi]
4276 [out]
4277 main:16: error: Signature of "foo" incompatible with supertype "BadParent"
4278 main:16: note: Superclass:
4279 main:16: note: @overload
4280 main:16: note: @classmethod
4281 main:16: note: def foo(cls, x: int) -> int
4282 main:16: note: @overload
4283 main:16: note: @classmethod
4284 main:16: note: def foo(cls, x: str) -> str
4285 main:16: note: Subclass:
4286 main:16: note: @overload
4287 main:16: note: def foo(cls, x: int) -> int
4288 main:16: note: @overload
4289 main:16: note: def foo(cls, x: str) -> str
4290
4291 [case testOverloadClassMethodImplementation]
4292 from typing import overload, Union
4293
4294 class Wrapper:
4295 @classmethod
4296 def other(cls) -> str:
4297 return "..."
4298
4299 @overload
4300 @classmethod
4301 def foo(cls, x: int) -> int: ...
4302
4303 @overload
4304 @classmethod
4305 def foo(cls, x: str) -> str: ...
4306
4307 @classmethod # E: Overloaded function implementation cannot produce return type of signature 1
4308 def foo(cls, x: Union[int, str]) -> str:
4309 reveal_type(cls) # N: Revealed type is "type[__main__.Wrapper]"
4310 reveal_type(cls.other()) # N: Revealed type is "builtins.str"
4311 return "..."
4312
4313 [builtins fixtures/classmethod.pyi]
4314
4315 [case testOverloadWithStaticMethods]
4316 from typing import overload
4317
4318 class Wrapper:
4319 @overload
4320 @staticmethod
4321 def foo(x: int) -> int: ...
4322 @overload
4323 @staticmethod
4324 def foo(x: str) -> str: ...
4325 @staticmethod
4326 def foo(x): pass
4327
4328 reveal_type(Wrapper.foo(3)) # N: Revealed type is "builtins.int"
4329 reveal_type(Wrapper.foo("foo")) # N: Revealed type is "builtins.str"
4330
4331 [builtins fixtures/staticmethod.pyi]
4332
4333 [case testOverloadWithInconsistentStaticMethods]
4334 from typing import overload, Union
4335
4336 class Wrapper1:
4337 @overload # E: Overload does not consistently use the "@staticmethod" decorator on all function signatures.
4338 @staticmethod
4339 def foo(x: int) -> int: ...
4340 @overload
4341 @staticmethod
4342 def foo(x: str) -> str: ...
4343 def foo(x): pass
4344
4345 class Wrapper2:
4346 @overload # E: Overload does not consistently use the "@staticmethod" decorator on all function signatures.
4347 @staticmethod
4348 def foo(x: int) -> int: ...
4349 @overload
4350 def foo(x: str) -> str: ... # E: "self" parameter missing for a non-static method (or an invalid type for self)
4351 @staticmethod
4352 def foo(x): pass
4353
4354 class Wrapper3:
4355 @overload # E: Overload does not consistently use the "@staticmethod" decorator on all function signatures.
4356 @staticmethod
4357 def foo(x: int) -> int: ...
4358 @overload
4359 @staticmethod
4360 def foo(x: str) -> str: ...
4361 def foo(x: Union[int, str]): pass # E: "self" parameter missing for a non-static method (or an invalid type for self)
4362 [builtins fixtures/staticmethod.pyi]
4363
4364 [case testOverloadWithSwappedDecorators2]
4365 from typing import overload
4366
4367 class Wrapper1:
4368 @staticmethod
4369 @overload
4370 def foo(x: int) -> int: ...
4371
4372 @staticmethod
4373 @overload
4374 def foo(x: str) -> str: ...
4375
4376 @staticmethod
4377 def foo(x): pass
4378
4379 class Wrapper2:
4380 @staticmethod
4381 @overload
4382 def foo(x: int) -> int: ...
4383
4384 @overload
4385 @staticmethod
4386 def foo(x: str) -> str: ...
4387
4388 @staticmethod
4389 def foo(x): pass
4390
4391 class Wrapper3:
4392 @staticmethod # E: Overload does not consistently use the "@staticmethod" decorator on all function signatures.
4393 @overload
4394 def foo(x: int) -> int: ...
4395
4396 @overload
4397 def foo(x: str) -> str: ... # E: "self" parameter missing for a non-static method (or an invalid type for self)
4398
4399 @staticmethod
4400 def foo(x): pass
4401
4402 reveal_type(Wrapper1.foo(3)) # N: Revealed type is "builtins.int"
4403 reveal_type(Wrapper2.foo(3)) # N: Revealed type is "builtins.int"
4404
4405 [builtins fixtures/staticmethod.pyi]
4406
4407 [case testOverloadFaultyStaticMethodInheritance]
4408 from typing import overload
4409
4410 class A: pass
4411 class B(A): pass
4412 class C(B): pass
4413
4414 class Parent:
4415 @overload
4416 @staticmethod
4417 def foo(x: B) -> int: ...
4418
4419 @overload
4420 @staticmethod
4421 def foo(x: str) -> str: ...
4422
4423 @staticmethod
4424 def foo(x): pass
4425
4426 class BadChild(Parent):
4427 @overload # Fail
4428 @staticmethod
4429 def foo(x: C) -> int: ...
4430
4431 @overload
4432 @staticmethod
4433 def foo(x: str) -> str: ...
4434
4435 @staticmethod
4436 def foo(x): pass
4437
4438 class GoodChild(Parent):
4439 @overload
4440 @staticmethod
4441 def foo(x: A) -> int: ...
4442
4443 @overload
4444 @staticmethod
4445 def foo(x: str) -> str: ...
4446
4447 @staticmethod
4448 def foo(x): pass
4449
4450 [builtins fixtures/staticmethod.pyi]
4451 [out]
4452 main:20: error: Signature of "foo" incompatible with supertype "Parent"
4453 main:20: note: Superclass:
4454 main:20: note: @overload
4455 main:20: note: @staticmethod
4456 main:20: note: def foo(x: B) -> int
4457 main:20: note: @overload
4458 main:20: note: @staticmethod
4459 main:20: note: def foo(x: str) -> str
4460 main:20: note: Subclass:
4461 main:20: note: @overload
4462 main:20: note: @staticmethod
4463 main:20: note: def foo(x: C) -> int
4464 main:20: note: @overload
4465 main:20: note: @staticmethod
4466 main:20: note: def foo(x: str) -> str
4467
4468 [case testOverloadStaticMethodMixingInheritance]
4469 from typing import overload
4470
4471 class BadParent:
4472 @overload
4473 @staticmethod
4474 def foo(x: int) -> int: ...
4475
4476 @overload
4477 @staticmethod
4478 def foo(x: str) -> str: ...
4479
4480 @staticmethod
4481 def foo(x): pass
4482
4483 class BadChild(BadParent):
4484 @overload # Fail
4485 def foo(self, x: int) -> int: ...
4486
4487 @overload
4488 def foo(self, x: str) -> str: ...
4489
4490 def foo(self, x): pass
4491
4492 class GoodParent:
4493 @overload
4494 def foo(self, x: int) -> int: ...
4495
4496 @overload
4497 def foo(self, x: str) -> str: ...
4498
4499 def foo(self, x): pass
4500
4501 class GoodChild(GoodParent):
4502 @overload
4503 @staticmethod
4504 def foo(x: int) -> int: ...
4505
4506 @overload
4507 @staticmethod
4508 def foo(x: str) -> str: ...
4509
4510 @staticmethod
4511 def foo(x): pass
4512
4513 [builtins fixtures/staticmethod.pyi]
4514 [out]
4515 main:16: error: Signature of "foo" incompatible with supertype "BadParent"
4516 main:16: note: Superclass:
4517 main:16: note: @overload
4518 main:16: note: @staticmethod
4519 main:16: note: def foo(x: int) -> int
4520 main:16: note: @overload
4521 main:16: note: @staticmethod
4522 main:16: note: def foo(x: str) -> str
4523 main:16: note: Subclass:
4524 main:16: note: @overload
4525 main:16: note: def foo(self, x: int) -> int
4526 main:16: note: @overload
4527 main:16: note: def foo(self, x: str) -> str
4528
4529 [case testOverloadStaticMethodImplementation]
4530 from typing import overload, Union
4531
4532 class Wrapper:
4533 @staticmethod
4534 def other() -> str:
4535 return "..."
4536
4537 @overload
4538 @staticmethod
4539 def foo(x: int) -> int: ...
4540
4541 @overload
4542 @staticmethod
4543 def foo(x: str) -> str: ...
4544
4545 @staticmethod # E: Overloaded function implementation cannot produce return type of signature 1
4546 def foo(x: Union[int, str]) -> str:
4547 return 3 # E: Incompatible return value type (got "int", expected "str")
4548
4549 [builtins fixtures/staticmethod.pyi]
4550
4551 [case testUnionMathOverloadingReturnsBestType]
4552 from typing import Union, overload
4553
4554 @overload
4555 def f(x: Union[int, str]) -> int: ...
4556 @overload
4557 def f(x: object) -> object: ...
4558 def f(x):
4559 pass
4560
4561 x: Union[int, str]
4562 reveal_type(f(x)) # N: Revealed type is "builtins.int"
4563 [out]
4564
4565 [case testOverloadAndSelfTypes]
4566 from typing import overload, Union, TypeVar, Type
4567
4568 T = TypeVar('T', bound='Parent')
4569 class Parent:
4570 @overload
4571 def foo(self: T, x: int) -> T: pass
4572
4573 @overload
4574 def foo(self, x: str) -> str: pass
4575
4576 def foo(self: T, x: Union[int, str]) -> Union[T, str]:
4577 reveal_type(self.bar()) # N: Revealed type is "builtins.str"
4578 return self
4579
4580 def bar(self) -> str: pass
4581
4582 class Child(Parent):
4583 def child_only(self) -> int: pass
4584
4585 x: Union[int, str]
4586 reveal_type(Parent().foo(3)) # N: Revealed type is "__main__.Parent"
4587 reveal_type(Child().foo(3)) # N: Revealed type is "__main__.Child"
4588 reveal_type(Child().foo("...")) # N: Revealed type is "builtins.str"
4589 reveal_type(Child().foo(x)) # N: Revealed type is "__main__.Child | builtins.str"
4590 reveal_type(Child().foo(3).child_only()) # N: Revealed type is "builtins.int"
4591
4592 [case testOverloadAndSelfTypesGenericNoOverlap]
4593 from typing import Generic, TypeVar, Any, overload, Self, Union
4594
4595 T = TypeVar("T")
4596 class C(Generic[T]):
4597 @overload
4598 def get(self, obj: None) -> Self: ...
4599 @overload
4600 def get(self, obj: Any) -> T: ...
4601 def get(self, obj: Union[Any, None]) -> Union[T, Self]:
4602 return self
4603
4604 class D(C[int]): ...
4605 d: D
4606 reveal_type(d.get(None)) # N: Revealed type is "__main__.D"
4607 reveal_type(d.get("whatever")) # N: Revealed type is "builtins.int"
4608
4609 [case testOverloadAndClassTypes]
4610 from typing import overload, Union, TypeVar, Type
4611
4612 T = TypeVar('T', bound='Parent')
4613 class Parent:
4614 @overload
4615 @classmethod
4616 def foo(cls: Type[T], x: int) -> Type[T]: pass
4617
4618 @overload
4619 @classmethod
4620 def foo(cls, x: str) -> str: pass
4621
4622 @classmethod
4623 def foo(cls: Type[T], x: Union[int, str]) -> Union[Type[T], str]:
4624 reveal_type(cls.bar()) # N: Revealed type is "builtins.str"
4625 return cls
4626
4627 @classmethod
4628 def bar(cls) -> str: pass
4629
4630 class Child(Parent):
4631 def child_only(self) -> int: pass
4632
4633 x: Union[int, str]
4634 reveal_type(Parent.foo(3)) # N: Revealed type is "type[__main__.Parent]"
4635 reveal_type(Child.foo(3)) # N: Revealed type is "type[__main__.Child]"
4636 reveal_type(Child.foo("...")) # N: Revealed type is "builtins.str"
4637 reveal_type(Child.foo(x)) # N: Revealed type is "type[__main__.Child] | builtins.str"
4638 reveal_type(Child.foo(3)().child_only()) # N: Revealed type is "builtins.int"
4639 [builtins fixtures/classmethod.pyi]
4640
4641 [case testOptionalIsNotAUnionIfNoStrictOverload]
4642 # flags: --no-strict-optional
4643 from typing import Optional, overload
4644
4645 class B: pass
4646 class C(B): pass
4647
4648 @overload
4649 def rp(x: C) -> C: ...
4650 @overload
4651 def rp(x: B) -> B: ...
4652 def rp(x):
4653 pass
4654
4655 x: Optional[C]
4656 reveal_type(rp(x)) # N: Revealed type is "__main__.C"
4657 [out]
4658
4659 [case testUnionMathTrickyOverload1]
4660 from typing import Union, overload
4661
4662 @overload
4663 def f(x: int, y: int) -> int: ...
4664 @overload
4665 def f(x: object, y: str) -> str: ...
4666 def f(x):
4667 pass
4668
4669 x: Union[int, str]
4670 y: Union[int, str]
4671 f(x, y)
4672 [out]
4673 main:12: error: Argument 1 to "f" has incompatible type "int | str"; expected "int"
4674 main:12: error: Argument 2 to "f" has incompatible type "int | str"; expected "int"
4675
4676 [case testUnionMathTrickyOverload2]
4677 from typing import overload, Union, Any
4678
4679 class C:
4680 def f(self, other: C) -> C: ...
4681
4682 class D(C):
4683 @overload
4684 def f(self, other: D) -> D: ...
4685 @overload
4686 def f(self, other: C) -> C: ...
4687 def f(self, other): ...
4688
4689 x: D
4690 y: Union[D, Any]
4691 reveal_type(x.f(y)) # N: Revealed type is "__main__.D | Any"
4692 [out]
4693
4694 [case testManyUnionsInOverload]
4695 from typing import overload, TypeVar, Union
4696
4697 T = TypeVar('T')
4698
4699 @overload
4700 def f(x: int, y: object, z: object, t: object, u: object, w: object, v: object, s: object) -> int: ...
4701 @overload
4702 def f(x: str, y: object, z: object, t: object, u: object, w: object, v: object, s: object) -> str: ...
4703 @overload
4704 def f(x: T, y: object, z: object, t: object, u: object, w: object, v: object, s: object) -> T: ...
4705 def f(*args, **kwargs):
4706 pass
4707
4708 class A: pass
4709 class B: pass
4710 x: Union[int, str, A, B]
4711 y = f(x, x, x, x, x, x, x, x) # 8 args
4712
4713 reveal_type(y) # N: Revealed type is "builtins.int | builtins.str | __main__.A | __main__.B"
4714 [builtins fixtures/dict.pyi]
4715 [out]
4716
4717 [case testOverloadsWithNoneComingSecondAreAlwaysFlaggedInNoStrictOptional]
4718 # flags: --no-strict-optional
4719 from typing import overload
4720
4721 @overload
4722 def none_first(x: None) -> None: ...
4723 @overload
4724 def none_first(x: int) -> int: ...
4725 def none_first(x: int) -> int:
4726 return x
4727
4728 @overload
4729 def none_second(x: int) -> int: ...
4730 @overload
4731 def none_second(x: None) -> None: ... # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
4732 def none_second(x: int) -> int:
4733 return x
4734
4735 [case testOverloadsWithNoneComingSecondIsOkInStrictOptional]
4736 from typing import overload, Optional
4737
4738 @overload
4739 def none_first(x: None) -> None: ...
4740 @overload
4741 def none_first(x: int) -> int: ...
4742 def none_first(x: Optional[int]) -> Optional[int]:
4743 return x
4744
4745 @overload
4746 def none_second(x: int) -> int: ...
4747 @overload
4748 def none_second(x: None) -> None: ...
4749 def none_second(x: Optional[int]) -> Optional[int]:
4750 return x
4751
4752 @overload
4753 def none_loose_impl(x: None) -> None: ...
4754 @overload
4755 def none_loose_impl(x: int) -> int: ...
4756 def none_loose_impl(x: int) -> int:
4757 return x
4758 [out]
4759 main:21: error: Overloaded function implementation does not accept all possible parameters of signature 1
4760 main:21: error: Overloaded function implementation cannot produce return type of signature 1
4761
4762 [case testTooManyUnionsException]
4763 from typing import overload, Union
4764
4765 @overload
4766 def f(*args: int) -> int: ...
4767 @overload
4768 def f(*args: str) -> str: ...
4769 def f(*args):
4770 pass
4771
4772 x: Union[int, str]
4773 f(x, x, x, x, x, x, x, x)
4774 [builtins fixtures/tuple.pyi]
4775 [out]
4776 main:11: error: Not all union combinations were tried because there are too many unions
4777 main:11: error: Argument 1 to "f" has incompatible type "int | str"; expected "int"
4778 main:11: error: Argument 2 to "f" has incompatible type "int | str"; expected "int"
4779 main:11: error: Argument 3 to "f" has incompatible type "int | str"; expected "int"
4780 main:11: error: Argument 4 to "f" has incompatible type "int | str"; expected "int"
4781 main:11: error: Argument 5 to "f" has incompatible type "int | str"; expected "int"
4782 main:11: error: Argument 6 to "f" has incompatible type "int | str"; expected "int"
4783 main:11: error: Argument 7 to "f" has incompatible type "int | str"; expected "int"
4784 main:11: error: Argument 8 to "f" has incompatible type "int | str"; expected "int"
4785
4786 [case testSafeDunderOverlapInSubclass]
4787 from typing import overload
4788
4789 class A:
4790 def __add__(self, x : 'A') -> 'A': ...
4791
4792 class B(A):
4793 @overload
4794 def __add__(self, x : 'B') -> 'B': ...
4795 @overload
4796 def __add__(self, x : 'A') -> 'A' : ...
4797 def __add__(self, x):
4798 pass
4799 [out]
4800
4801 [case testUnsafeDunderOverlapInSubclass]
4802 from typing import overload
4803
4804 class A:
4805 def __add__(self, x : 'A') -> 'A':
4806 if isinstance(x, A):
4807 return A()
4808 else:
4809 return NotImplemented
4810
4811 # This is unsafe override because of the problem below
4812 class B(A):
4813 @overload # Fail
4814 def __add__(self, x : 'Other') -> 'B' : ...
4815 @overload
4816 def __add__(self, x : 'A') -> 'A': ...
4817 def __add__(self, x):
4818 if isinstance(x, Other):
4819 return B()
4820 elif isinstance(x, A):
4821 return A()
4822 else:
4823 return NotImplemented
4824
4825 class Other:
4826 def __radd__(self, x: 'A') -> 'Other':
4827 if isinstance(x, A):
4828 return Other()
4829 else:
4830 return NotImplemented
4831
4832 actually_b: A = B()
4833 reveal_type(actually_b + Other()) # Note
4834 # Runtime type is B, this is why we report the error on overriding.
4835 [builtins fixtures/isinstance.pyi]
4836 [out]
4837 main:12: error: Signature of "__add__" incompatible with supertype "A"
4838 main:12: note: Superclass:
4839 main:12: note: def __add__(self, A, /) -> A
4840 main:12: note: Subclass:
4841 main:12: note: @overload
4842 main:12: note: def __add__(self, Other, /) -> B
4843 main:12: note: @overload
4844 main:12: note: def __add__(self, A, /) -> A
4845 main:12: note: Overloaded operator methods can't have wider argument types in overrides
4846 main:32: note: Revealed type is "__main__.Other"
4847
4848 [case testOverloadErrorMessageManyMatches]
4849 from typing import overload
4850
4851 class A: pass
4852 class B: pass
4853 class C: pass
4854 class D: pass
4855
4856 @overload
4857 def f(x: A) -> None: ...
4858 @overload
4859 def f(x: B) -> None: ...
4860 @overload
4861 def f(x: C) -> None: ...
4862 @overload
4863 def f(x: D) -> None: ...
4864 @overload
4865 def f(x: int, y: int) -> None: ...
4866 def f(*args): pass
4867
4868 f(3) # E: No overload variant of "f" matches argument type "int" \
4869 # N: Possible overload variants: \
4870 # N: def f(x: A) -> None \
4871 # N: def f(x: B) -> None \
4872 # N: def f(x: C) -> None \
4873 # N: def f(x: D) -> None \
4874 # N: def f(x: int, y: int) -> None
4875
4876 @overload
4877 def g(x: A) -> None: ...
4878 @overload
4879 def g(x: B) -> None: ...
4880 @overload
4881 def g(x: C) -> None: ...
4882 def g(*args): pass
4883
4884 g(3) # E: No overload variant of "g" matches argument type "int" \
4885 # N: Possible overload variants: \
4886 # N: def g(x: A) -> None \
4887 # N: def g(x: B) -> None \
4888 # N: def g(x: C) -> None
4889 [builtins fixtures/tuple.pyi]
4890
4891 [case testOverloadedInIter]
4892 from lib import f, g
4893
4894 for fun in [f, g]:
4895 reveal_type(fun) # N: Revealed type is "Overload(def (x: builtins.int) -> builtins.str, def (x: builtins.str) -> builtins.int)"
4896 [file lib.pyi]
4897 from typing import overload
4898
4899 @overload
4900 def f(x: int) -> str: ...
4901 @overload
4902 def f(x: str) -> int: ...
4903
4904 @overload
4905 def g(x: int) -> str: ...
4906 @overload
4907 def g(x: str) -> int: ...
4908
4909 [builtins fixtures/list.pyi]
4910 [typing fixtures/typing-medium.pyi]
4911 [out]
4912
4913 [case testNestedOverloadsNoCrash]
4914 from typing import overload
4915
4916 def f() -> None:
4917 @overload
4918 def g(x: str) -> str: ...
4919 @overload
4920 def g(x: int) -> int: ...
4921 def g(x):
4922 pass
4923 g(str())
4924 [out]
4925
4926 [case testNestedOverloadsTypeVar]
4927 from typing import overload, TypeVar
4928
4929 T = TypeVar('T')
4930
4931 def f() -> None:
4932 @overload
4933 def g(x: str) -> str: ...
4934 @overload
4935 def g(x: T, y: int) -> T: ...
4936 def g(x):
4937 pass
4938
4939 g(str(), str()) # E: No overload variant of "g" matches argument types "str", "str" \
4940 # N: Possible overload variants: \
4941 # N: def g(x: str) -> str \
4942 # N: def [T] g(x: T, y: int) -> T
4943 reveal_type(g(str(), int())) # N: Revealed type is "builtins.str"
4944 [out]
4945
4946 [case testNestedOverloadsTypeVarOverlap]
4947 from typing import overload, TypeVar
4948
4949 T = TypeVar('T')
4950
4951 def f() -> None:
4952 @overload
4953 def g(x: str) -> int: ...
4954 @overload
4955 def g(x: T) -> T: ...
4956 def g(x):
4957 pass
4958 [out]
4959
4960 [case testNestedOverloadsMutuallyRecursive]
4961 from typing import overload, TypeVar, Dict, Any
4962
4963 class C: ...
4964 T = TypeVar('T')
4965
4966 def f() -> None:
4967 @overload
4968 def g() -> None: ...
4969 @overload
4970 def g(x: T) -> Dict[int, T]: ...
4971 def g(*args, **kwargs) -> Any:
4972 reveal_type(h(C())) # N: Revealed type is "builtins.dict[builtins.str, __main__.C]"
4973
4974 @overload
4975 def h() -> None: ...
4976 @overload
4977 def h(x: T) -> Dict[str, T]: ...
4978 def h(*args, **kwargs) -> Any:
4979 reveal_type(g(C())) # N: Revealed type is "builtins.dict[builtins.int, __main__.C]"
4980
4981 [builtins fixtures/dict.pyi]
4982 [out]
4983
4984 [case testOverloadConstrainedTypevarNotShadowingAny]
4985 from lib import attr
4986 from typing import Any
4987
4988 reveal_type(attr(1)) # N: Revealed type is "builtins.int"
4989 reveal_type(attr("hi")) # N: Revealed type is "builtins.int"
4990 x: Any
4991 reveal_type(attr(x)) # N: Revealed type is "Any"
4992 attr("hi", 1) # E: No overload variant of "attr" matches argument types "str", "int" \
4993 # N: Possible overload variants: \
4994 # N: def [T: (int, float)] attr(default: T, blah: int = ...) -> T \
4995 # N: def attr(default: Any = ...) -> int
4996 [file lib.pyi]
4997 from typing import overload, Any, TypeVar
4998
4999 T = TypeVar('T', int, float)
5000
5001 @overload
5002 def attr(default: T, blah: int = ...) -> T: ...
5003 @overload
5004 def attr(default: Any = ...) -> int: ...
5005 [out]
5006
5007 [case testOverloadBoundedTypevarNotShadowingAny]
5008 from lib import attr
5009 from typing import Any
5010
5011 reveal_type(attr(1)) # N: Revealed type is "builtins.int"
5012 reveal_type(attr("hi")) # N: Revealed type is "builtins.int"
5013 x: Any
5014 reveal_type(attr(x)) # N: Revealed type is "Any"
5015 attr("hi", 1) # E: No overload variant of "attr" matches argument types "str", "int" \
5016 # N: Possible overload variants: \
5017 # N: def [T: int] attr(default: T = ..., blah: int = ...) -> T \
5018 # N: def attr(default: Any = ...) -> int
5019 [file lib.pyi]
5020 from typing import overload, TypeVar, Any
5021
5022 T = TypeVar('T', bound=int)
5023
5024 @overload
5025 def attr(default: T = ..., blah: int = ...) -> T: ...
5026 @overload
5027 def attr(default: Any = ...) -> int: ...
5028 [out]
5029
5030 [case testAnyIsOKAsFallbackInOverloads]
5031 import stub
5032 [file stub.pyi]
5033 from typing import TypeVar, Any, overload
5034
5035 T = TypeVar('T')
5036
5037 @overload
5038 def foo(x: T) -> T: ...
5039 @overload
5040 def foo(x: Any) -> Any: ...
5041
5042 @overload
5043 def bar(x: T) -> T: ...
5044 @overload
5045 def bar(x: Any) -> int: ...
5046 [out]
5047
5048 [case testOverloadsIgnorePromotions]
5049 from typing import overload, List, Union, _promote
5050
5051 class Parent: pass
5052 class Child(Parent): pass
5053
5054 children: List[Child]
5055 parents: List[Parent]
5056
5057 @overload
5058 def f(x: Child) -> List[Child]: pass
5059 @overload
5060 def f(x: Parent) -> List[Parent]: pass
5061 def f(x: Union[Child, Parent]) -> Union[List[Child], List[Parent]]:
5062 if isinstance(x, Child):
5063 reveal_type(x) # N: Revealed type is "__main__.Child"
5064 return children
5065 else:
5066 reveal_type(x) # N: Revealed type is "__main__.Parent"
5067 return parents
5068
5069 ints: List[int]
5070 floats: List[float]
5071
5072 @overload
5073 def g(x: int) -> List[int]: pass
5074 @overload
5075 def g(x: float) -> List[float]: pass
5076 def g(x: Union[int, float]) -> Union[List[int], List[float]]:
5077 if isinstance(x, int):
5078 reveal_type(x) # N: Revealed type is "builtins.int"
5079 return ints
5080 else:
5081 reveal_type(x) # N: Revealed type is "builtins.float"
5082 return floats
5083
5084 [builtins fixtures/isinstancelist.pyi]
5085 [typing fixtures/typing-medium.pyi]
5086
5087 [case testOverloadsTypesAndUnions]
5088 from typing import overload, Type, Union
5089
5090 class A: pass
5091 class B: pass
5092
5093 @overload
5094 def f(x: Type[A]) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
5095 @overload
5096 def f(x: Union[Type[A], Type[B]]) -> str: ...
5097 def f(x: Union[Type[A], Type[B]]) -> Union[int, str]:
5098 return 1
5099
5100 [case testBadOverloadProbableMatch]
5101 from typing import overload, List, Type
5102
5103 class Other: pass
5104
5105 @overload
5106 def multiple_plausible(x: int) -> int: ...
5107 @overload
5108 def multiple_plausible(x: str) -> str: ...
5109 def multiple_plausible(x): pass
5110
5111
5112 @overload
5113 def single_plausible(x: Type[int]) -> int: ...
5114 @overload
5115 def single_plausible(x: List[str]) -> str: ...
5116 def single_plausible(x): pass
5117
5118 a = multiple_plausible(Other()) # E: No overload variant of "multiple_plausible" matches argument type "Other" \
5119 # N: Possible overload variants: \
5120 # N: def multiple_plausible(x: int) -> int \
5121 # N: def multiple_plausible(x: str) -> str
5122 reveal_type(a) # N: Revealed type is "Any"
5123
5124 b = single_plausible(Other) # E: Argument 1 to "single_plausible" has incompatible type "type[Other]"; expected "type[int]"
5125 reveal_type(b) # N: Revealed type is "builtins.int"
5126
5127 c = single_plausible([Other()]) # E: List item 0 has incompatible type "Other"; expected "str"
5128 reveal_type(c) # N: Revealed type is "builtins.str"
5129 [builtins fixtures/list.pyi]
5130
5131 [case testDisallowUntypedDecoratorsOverload]
5132 # flags: --disallow-untyped-decorators
5133 from typing import Any, Callable, overload, TypeVar
5134
5135 F = TypeVar('F', bound=Callable[..., Any])
5136
5137 @overload
5138 def dec(x: F) -> F: ...
5139 @overload
5140 def dec(x: str) -> Callable[[F], F]: ...
5141 def dec(x) -> Any:
5142 pass
5143
5144 @dec
5145 def f(name: str) -> int:
5146 return 0
5147
5148 @dec('abc')
5149 def g(name: str) -> int:
5150 return 0
5151
5152 reveal_type(f) # N: Revealed type is "def (name: builtins.str) -> builtins.int"
5153 reveal_type(g) # N: Revealed type is "def (name: builtins.str) -> builtins.int"
5154
5155 [case testDisallowUntypedDecoratorsOverloadDunderCall]
5156 # flags: --disallow-untyped-decorators
5157 from typing import Any, Callable, overload, TypeVar
5158
5159 F = TypeVar('F', bound=Callable[..., Any])
5160
5161 class Dec:
5162 @overload
5163 def __call__(self, x: F) -> F: ...
5164 @overload
5165 def __call__(self, x: str) -> Callable[[F], F]: ...
5166 def __call__(self, x) -> Any:
5167 pass
5168
5169 dec = Dec()
5170
5171 @dec
5172 def f(name: str) -> int:
5173 return 0
5174
5175 @dec('abc')
5176 def g(name: str) -> int:
5177 return 0
5178
5179 reveal_type(f) # N: Revealed type is "def (name: builtins.str) -> builtins.int"
5180 reveal_type(g) # N: Revealed type is "def (name: builtins.str) -> builtins.int"
5181
5182 [case testOverloadBadArgumentsInferredToAny1]
5183 from typing import Union, Any, overload
5184
5185 def bar(x: int) -> Union[int, Any]: ...
5186
5187 @overload
5188 def foo(x: str) -> None: ...
5189 @overload
5190 def foo(x: int) -> None: ...
5191 def foo(x) -> None: pass
5192
5193 foo(bar('lol')) # E: Argument 1 to "bar" has incompatible type "str"; expected "int"
5194
5195 [case testOverloadBadArgumentsInferredToAny2]
5196 from typing import Union, Iterable, Tuple, TypeVar, Generic, overload, Any
5197
5198 class A:
5199 def foo(self) -> Iterable[int]: pass
5200
5201 def bar(x: int) -> Union[A, int]: ...
5202
5203 _T = TypeVar('_T')
5204
5205 @overload
5206 def foo() -> None: ...
5207 @overload
5208 def foo(iterable: Iterable[_T]) -> None: ...
5209 def foo(iterable = None) -> None: pass
5210
5211 foo(bar('lol').foo()) # E: Item "int" of "A | int" has no attribute "foo" \
5212 # E: Argument 1 to "bar" has incompatible type "str"; expected "int"
5213
5214
5215 [case testOverloadInferringArgumentsUsingContext1]
5216 from typing import Optional, List, overload, TypeVar
5217 T = TypeVar('T')
5218
5219 def g(x: Optional[T] = None) -> List[T]: ...
5220
5221 @overload
5222 def f(x: int) -> int: ...
5223 @overload
5224 def f(x: List[int]) -> List[int]: ...
5225 def f(x): pass
5226
5227 reveal_type(f(g())) # N: Revealed type is "builtins.list[builtins.int]"
5228 [builtins fixtures/list.pyi]
5229
5230 [case testOverloadInferringArgumentsUsingContext2-skip]
5231 # TODO: Overloads only use outer context to infer type variables in a given overload variant,
5232 # but never use outer context to _choose_ a better overload in ambiguous situations
5233 # like empty containers or multiple inheritance, instead just always choosing the first one.
5234
5235 from typing import Optional, List, overload, TypeVar
5236 T = TypeVar('T')
5237 @overload
5238 def g(x: List[str]) -> List[str]: ...
5239 @overload
5240 def g(x: List[int]) -> List[int]: ...
5241 def g(x):
5242 pass
5243
5244 @overload
5245 def f(x: int) -> int: ...
5246 @overload
5247 def f(x: List[int]) -> List[int]: ...
5248 def f(x):
5249 pass
5250
5251 reveal_type(f(g([]))) # N: Revealed type is "builtins.list[builtins.int]"
5252 [builtins fixtures/list.pyi]
5253
5254 [case testOverloadDeferredNode]
5255 from typing import Callable, TypeVar, Generic, Any, overload
5256
5257 _S = TypeVar('_S')
5258 _T = TypeVar('_T')
5259 _R = TypeVar('_R')
5260
5261 @overload
5262 def partial(__func: Callable[[_T], _S], __arg: _T) -> Callable[[], _S]: ...
5263 @overload
5264 def partial(__func: Callable[[_T, _S], _S], __arg: _T) -> Callable[[_S], _R]: ...
5265 def partial(*args: Any) -> Any:
5266 pass
5267
5268 def f(f: Callable[[int], int]) -> None:
5269 pass
5270
5271 def dec(f: Callable[[_S, _T], _R]) -> Callable[[_S, _T], _R]: pass
5272
5273 def asdf() -> None:
5274 f(partial(lol, 0))
5275
5276 @dec
5277 def lol(x: int, y: int) -> int:
5278 pass
5279 [builtins fixtures/tuple.pyi]
5280
5281 [case testVeryBrokenOverload]
5282 import lib
5283 reveal_type(lib.func) # N: Revealed type is "Any"
5284 [file lib.pyi]
5285 @overload # E: Name "overload" is not defined
5286 def func(x: int) -> int: ...
5287
5288 def func(x): # E: Name "func" already defined on line 1
5289 return x
5290
5291 -- Order of errors is different
5292 [case testVeryBrokenOverload2]
5293
5294 import lib
5295 reveal_type(lib.func) # N: Revealed type is "Any"
5296 [file lib.pyi]
5297 @overload # E: Name "overload" is not defined
5298 def func(x: int) -> int: ...
5299 @overload # E: Name "func" already defined on line 1 # E: Name "overload" is not defined
5300 def func(x: str) -> str: ...
5301
5302 [case testLiteralSubtypeOverlap]
5303 from typing import Literal, overload
5304
5305 class MyInt(int): ...
5306
5307 # Strictly speaking we can't prove this is unsafe (this depends on the implementation),
5308 # but such APIs seem like an anti-pattern anyways.
5309 @overload
5310 def foo(x: Literal[0]) -> None: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
5311 @overload
5312 def foo(x: MyInt) -> int: ...
5313 def foo(x):
5314 ...
5315 [builtins fixtures/tuple.pyi]
5316
5317 [case testOverloadedToGeneric]
5318 from typing import TypeVar, Callable, NewType, overload, Union
5319
5320 # int in our stubs isn't overloaded
5321 class fakeint:
5322 @overload
5323 def __init__(self, x: Union[str, bytes] = ...) -> None: ...
5324 @overload
5325 def __init__(self, x: Union[str, bytes], base: int) -> None: ...
5326 def __init__(self, *args) -> None: pass # type: ignore
5327
5328
5329 U = TypeVar('U')
5330 V = TypeVar('V')
5331 W = TypeVar('W')
5332 def compose(f: Callable[[U], V], g: Callable[[W], U]) -> Callable[[W], V]:
5333 return lambda x: f(g(x))
5334
5335 ID = NewType("ID", fakeint)
5336
5337 compose(ID, fakeint)("test")
5338 reveal_type(compose(ID, fakeint)) # N: Revealed type is "def (builtins.str | builtins.bytes) -> __main__.ID"
5339
5340 [builtins fixtures/tuple.pyi]
5341
5342 [case testOverloadTwoTypeArgs]
5343 from typing import Generic, overload, TypeVar, Any
5344
5345 T1 = TypeVar("T1")
5346 T2 = TypeVar("T2")
5347
5348 class A: ...
5349 class B: ...
5350 class G(Generic[T1, T2]): ...
5351
5352 @overload
5353 def f1(g: G[A, A]) -> A: ...
5354 @overload
5355 def f1(g: G[A, B]) -> B: ...
5356 def f1(g: Any) -> Any: ...
5357
5358 @overload
5359 def f2(g: G[A, Any]) -> A: ...
5360 @overload
5361 def f2(g: G[A, B], x: int = ...) -> B: ...
5362 def f2(g: Any, x: int = ...) -> Any: ...
5363
5364 [case testOverloadTypeVsCallable]
5365 from typing import TypeVar, Type, Callable, Any, overload, Optional
5366 class Foo:
5367 def __init__(self, **kwargs: Any): pass
5368 _T = TypeVar('_T')
5369 @overload
5370 def register(cls: Type[_T]) -> int: ...
5371 @overload
5372 def register(cls: Callable[..., _T]) -> Optional[int]: ...
5373 def register(cls: Any) -> Any: return None
5374
5375
5376 x = register(Foo)
5377 reveal_type(x) # N: Revealed type is "builtins.int"
5378 [builtins fixtures/dict.pyi]
5379
5380
5381 [case testOverloadWithObjectDecorator]
5382 from typing import Any, Callable, Union, overload
5383
5384 class A:
5385 def __call__(self, *arg, **kwargs) -> None: ...
5386
5387 def dec_a(f: Callable[..., Any]) -> A:
5388 return A()
5389
5390 @overload
5391 def f_a(arg: int) -> None: ...
5392 @overload
5393 def f_a(arg: str) -> None: ...
5394 @dec_a
5395 def f_a(arg): ...
5396
5397 class B:
5398 def __call__(self, arg: Union[int, str]) -> None: ...
5399
5400 def dec_b(f: Callable[..., Any]) -> B:
5401 return B()
5402
5403 @overload
5404 def f_b(arg: int) -> None: ...
5405 @overload
5406 def f_b(arg: str) -> None: ...
5407 @dec_b
5408 def f_b(arg): ...
5409
5410 class C:
5411 def __call__(self, arg: int) -> None: ...
5412
5413 def dec_c(f: Callable[..., Any]) -> C:
5414 return C()
5415
5416 @overload
5417 def f_c(arg: int) -> None: ...
5418 @overload
5419 def f_c(arg: str) -> None: ...
5420 @dec_c # E: Overloaded function implementation does not accept all possible parameters of signature 2
5421 def f_c(arg): ...
5422 [builtins fixtures/dict.pyi]
5423
5424 [case testOverloadWithErrorDecorator]
5425 from typing import Any, Callable, TypeVar, overload
5426
5427 def dec_d(f: Callable[..., Any]) -> int: ...
5428
5429 @overload
5430 def f_d(arg: int) -> None: ...
5431 @overload
5432 def f_d(arg: str) -> None: ...
5433 @dec_d # E: "int" not callable
5434 def f_d(arg): ...
5435
5436 Bad1 = TypeVar('Good') # type: ignore
5437
5438 def dec_e(f: Bad1) -> Bad1: ... # type: ignore
5439
5440 @overload
5441 def f_e(arg: int) -> None: ...
5442 @overload
5443 def f_e(arg: str) -> None: ...
5444 @dec_e # E: Bad1? not callable
5445 def f_e(arg): ...
5446
5447 class Bad2:
5448 def __getattr__(self, attr):
5449 # __getattr__ is not called for implicit `__call__`
5450 if attr == "__call__":
5451 return lambda *a, **kw: print(a, kw)
5452 raise AttributeError
5453
5454 @overload
5455 def f_f(arg: int) -> None: ...
5456 @overload
5457 def f_f(arg: str) -> None: ...
5458 @Bad2() # E: "Bad2" not callable
5459 def f_f(arg): ...
5460 [builtins fixtures/dict.pyi]
5461
5462
5463 [case testOverloadIfBasic]
5464 # flags: --always-true True --always-false False
5465 from typing import overload
5466
5467 class A: ...
5468 class B: ...
5469 class C: ...
5470 class D: ...
5471
5472 # -----
5473 # Test basic overload merging
5474 # -----
5475
5476 @overload
5477 def f1(g: A) -> A: ...
5478 if True:
5479 @overload
5480 def f1(g: B) -> B: ...
5481 def f1(g): ...
5482 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
5483 reveal_type(f1(B())) # N: Revealed type is "__main__.B"
5484
5485 @overload
5486 def f2(g: A) -> A: ...
5487 @overload
5488 def f2(g: B) -> B: ...
5489 if False:
5490 @overload
5491 def f2(g: C) -> C: ...
5492 def f2(g): ...
5493 reveal_type(f2(A())) # N: Revealed type is "__main__.A"
5494 reveal_type(f2(C())) # E: No overload variant of "f2" matches argument type "C" \
5495 # N: Possible overload variants: \
5496 # N: def f2(g: A) -> A \
5497 # N: def f2(g: B) -> B \
5498 # N: Revealed type is "Any"
5499
5500 @overload
5501 def f3(g: A) -> A: ...
5502 @overload
5503 def f3(g: B) -> B: ...
5504 if maybe_true: # E: Condition can't be inferred, unable to merge overloads \
5505 # E: Name "maybe_true" is not defined
5506 @overload
5507 def f3(g: C) -> C: ...
5508 def f3(g): ...
5509 reveal_type(f3(A())) # N: Revealed type is "__main__.A"
5510 reveal_type(f3(C())) # E: No overload variant of "f3" matches argument type "C" \
5511 # N: Possible overload variants: \
5512 # N: def f3(g: A) -> A \
5513 # N: def f3(g: B) -> B \
5514 # N: Revealed type is "Any"
5515
5516 if True:
5517 @overload
5518 def f4(g: A) -> A: ...
5519 if True:
5520 @overload
5521 def f4(g: B) -> B: ...
5522 @overload
5523 def f4(g: C) -> C: ...
5524 def f4(g): ...
5525 reveal_type(f4(A())) # N: Revealed type is "__main__.A"
5526 reveal_type(f4(B())) # N: Revealed type is "__main__.B"
5527 reveal_type(f4(C())) # N: Revealed type is "__main__.C"
5528
5529 if True:
5530 @overload
5531 def f5(g: A) -> A: ...
5532 @overload
5533 def f5(g: B) -> B: ...
5534 if True:
5535 @overload
5536 def f5(g: C) -> C: ...
5537 @overload
5538 def f5(g: D) -> D: ...
5539 def f5(g): ...
5540 reveal_type(f5(A())) # N: Revealed type is "__main__.A"
5541 reveal_type(f5(B())) # N: Revealed type is "__main__.B"
5542 reveal_type(f5(C())) # N: Revealed type is "__main__.C"
5543 reveal_type(f5(D())) # N: Revealed type is "__main__.D"
5544
5545 [case testOverloadIfSysVersion]
5546 # flags: --python-version 3.10
5547 from typing import overload
5548 import sys
5549
5550 class A: ...
5551 class B: ...
5552 class C: ...
5553
5554 # -----
5555 # "Real" world example
5556 # Test overload merging for sys.version_info
5557 # -----
5558
5559 @overload
5560 def f1(g: A) -> A: ...
5561 if sys.version_info >= (3, 10):
5562 @overload
5563 def f1(g: B) -> B: ...
5564 def f1(g): ...
5565 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
5566 reveal_type(f1(B())) # N: Revealed type is "__main__.B"
5567
5568 @overload
5569 def f2(g: A) -> A: ...
5570 @overload
5571 def f2(g: B) -> B: ...
5572 if sys.version_info >= (3, 11):
5573 @overload
5574 def f2(g: C) -> C: ...
5575 def f2(g): ...
5576 reveal_type(f2(A())) # N: Revealed type is "__main__.A"
5577 reveal_type(f2(C())) # E: No overload variant of "f2" matches argument type "C" \
5578 # N: Possible overload variants: \
5579 # N: def f2(g: A) -> A \
5580 # N: def f2(g: B) -> B \
5581 # N: Revealed type is "Any"
5582 [builtins fixtures/ops.pyi]
5583
5584 [case testOverloadIfMerging]
5585 # flags: --always-true True
5586 from typing import overload
5587
5588 class A: ...
5589 class B: ...
5590 class C: ...
5591
5592 # -----
5593 # Test overload merging
5594 # -----
5595
5596 @overload
5597 def f1(g: A) -> A: ...
5598 if True:
5599 # Some comment
5600 @overload
5601 def f1(g: B) -> B: ...
5602 def f1(g): ...
5603 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
5604 reveal_type(f1(B())) # N: Revealed type is "__main__.B"
5605
5606 @overload
5607 def f2(g: A) -> A: ...
5608 if True:
5609 @overload
5610 def f2(g: bytes) -> B: ...
5611 @overload
5612 def f2(g: B) -> C: ...
5613 def f2(g): ...
5614 reveal_type(f2(A())) # N: Revealed type is "__main__.A"
5615 reveal_type(f2(B())) # N: Revealed type is "__main__.C"
5616
5617 @overload
5618 def f3(g: A) -> A: ...
5619 @overload
5620 def f3(g: B) -> B: ...
5621 if True:
5622 def f3(g): ...
5623 reveal_type(f3(A())) # N: Revealed type is "__main__.A"
5624 reveal_type(f3(B())) # N: Revealed type is "__main__.B"
5625
5626 if True:
5627 @overload
5628 def f4(g: A) -> A: ...
5629 @overload
5630 def f4(g: B) -> B: ...
5631 def f4(g): ...
5632 reveal_type(f4(A())) # N: Revealed type is "__main__.A"
5633 reveal_type(f4(B())) # N: Revealed type is "__main__.B"
5634
5635 if True:
5636 # Some comment
5637 @overload
5638 def f5(g: A) -> A: ...
5639 @overload
5640 def f5(g: B) -> B: ...
5641 def f5(g): ...
5642 reveal_type(f5(A())) # N: Revealed type is "__main__.A"
5643 reveal_type(f5(B())) # N: Revealed type is "__main__.B"
5644
5645 [case testOverloadIfNotMerging]
5646 # flags: --always-true True
5647 from typing import overload
5648
5649 class A: ...
5650 class B: ...
5651 class C: ...
5652
5653 # -----
5654 # Don't merge if IfStmt contains nodes other than overloads
5655 # -----
5656
5657 @overload # E: An overloaded function outside a stub file must have an implementation
5658 def f1(g: A) -> A: ...
5659 @overload
5660 def f1(g: B) -> B: ...
5661 if True:
5662 @overload # E: Name "f1" already defined on line 12 \
5663 # E: Single overload definition, multiple required
5664 def f1(g: C) -> C: ...
5665 pass # Some other action
5666 def f1(g): ... # E: Name "f1" already defined on line 12
5667 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
5668 reveal_type(f1(C())) # E: No overload variant of "f1" matches argument type "C" \
5669 # N: Possible overload variants: \
5670 # N: def f1(g: A) -> A \
5671 # N: def f1(g: B) -> B \
5672 # N: Revealed type is "Any"
5673
5674 if True:
5675 pass # Some other action
5676 @overload # E: Single overload definition, multiple required
5677 def f2(g: A) -> A: ...
5678 @overload # E: Name "f2" already defined on line 26
5679 def f2(g: B) -> B: ...
5680 @overload
5681 def f2(g: C) -> C: ...
5682 def f2(g): ...
5683 reveal_type(f2(A())) # N: Revealed type is "__main__.A"
5684 reveal_type(f2(C())) # N: Revealed type is "__main__.A" \
5685 # E: Argument 1 to "f2" has incompatible type "C"; expected "A"
5686
5687 [case testOverloadIfOldStyle]
5688 # flags: --always-false var_false --always-true var_true
5689 from typing import overload
5690
5691 class A: ...
5692 class B: ...
5693
5694 # -----
5695 # Test old style to make sure it still works
5696 # -----
5697
5698 var_true = True
5699 var_false = False
5700
5701 if var_false:
5702 @overload
5703 def f1(g: A) -> A: ...
5704 @overload
5705 def f1(g: B) -> B: ...
5706 def f1(g): ...
5707 elif var_true:
5708 @overload
5709 def f1(g: A) -> A: ...
5710 @overload
5711 def f1(g: B) -> B: ...
5712 def f1(g): ...
5713 else:
5714 @overload
5715 def f1(g: A) -> A: ...
5716 @overload
5717 def f1(g: B) -> B: ...
5718 def f1(g): ...
5719 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
5720 reveal_type(f1(B())) # N: Revealed type is "__main__.B"
5721
5722 [case testOverloadIfElse]
5723 # flags: --always-true True --always-false False
5724 from typing import overload
5725
5726 class A: ...
5727 class B: ...
5728 class C: ...
5729 class D: ...
5730
5731 # -----
5732 # Match the first always-true block
5733 # -----
5734
5735 @overload
5736 def f1(x: A) -> A: ...
5737 if True:
5738 @overload
5739 def f1(x: B) -> B: ...
5740 elif False:
5741 @overload
5742 def f1(x: C) -> C: ...
5743 else:
5744 @overload
5745 def f1(x: D) -> D: ...
5746 def f1(x): ...
5747 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
5748 reveal_type(f1(B())) # N: Revealed type is "__main__.B"
5749 reveal_type(f1(C())) # E: No overload variant of "f1" matches argument type "C" \
5750 # N: Possible overload variants: \
5751 # N: def f1(x: A) -> A \
5752 # N: def f1(x: B) -> B \
5753 # N: Revealed type is "Any"
5754
5755 @overload
5756 def f2(x: A) -> A: ...
5757 if False:
5758 @overload
5759 def f2(x: B) -> B: ...
5760 elif True:
5761 @overload
5762 def f2(x: C) -> C: ...
5763 else:
5764 @overload
5765 def f2(x: D) -> D: ...
5766 def f2(x): ...
5767 reveal_type(f2(A())) # N: Revealed type is "__main__.A"
5768 reveal_type(f2(B())) # E: No overload variant of "f2" matches argument type "B" \
5769 # N: Possible overload variants: \
5770 # N: def f2(x: A) -> A \
5771 # N: def f2(x: C) -> C \
5772 # N: Revealed type is "Any"
5773 reveal_type(f2(C())) # N: Revealed type is "__main__.C"
5774
5775 @overload
5776 def f3(x: A) -> A: ...
5777 if False:
5778 @overload
5779 def f3(x: B) -> B: ...
5780 elif False:
5781 @overload
5782 def f3(x: C) -> C: ...
5783 else:
5784 @overload
5785 def f3(x: D) -> D: ...
5786 def f3(x): ...
5787 reveal_type(f3(A())) # N: Revealed type is "__main__.A"
5788 reveal_type(f3(C())) # E: No overload variant of "f3" matches argument type "C" \
5789 # N: Possible overload variants: \
5790 # N: def f3(x: A) -> A \
5791 # N: def f3(x: D) -> D \
5792 # N: Revealed type is "Any"
5793 reveal_type(f3(D())) # N: Revealed type is "__main__.D"
5794
5795 [case testOverloadIfElse2]
5796 # flags: --always-true True
5797 from typing import overload
5798
5799 class A: ...
5800 class B: ...
5801 class C: ...
5802 class D: ...
5803
5804 # -----
5805 # Match the first always-true block
5806 # Don't merge overloads if can't be certain about execution of block
5807 # -----
5808
5809 @overload
5810 def f1(x: A) -> A: ...
5811 if True:
5812 @overload
5813 def f1(x: B) -> B: ...
5814 else:
5815 @overload
5816 def f1(x: D) -> D: ...
5817 def f1(x): ...
5818 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
5819 reveal_type(f1(B())) # N: Revealed type is "__main__.B"
5820 reveal_type(f1(D())) # E: No overload variant of "f1" matches argument type "D" \
5821 # N: Possible overload variants: \
5822 # N: def f1(x: A) -> A \
5823 # N: def f1(x: B) -> B \
5824 # N: Revealed type is "Any"
5825
5826 @overload
5827 def f2(x: A) -> A: ...
5828 if True:
5829 @overload
5830 def f2(x: B) -> B: ...
5831 elif maybe_true:
5832 @overload
5833 def f2(x: C) -> C: ...
5834 else:
5835 @overload
5836 def f2(x: D) -> D: ...
5837 def f2(x): ...
5838 reveal_type(f2(A())) # N: Revealed type is "__main__.A"
5839 reveal_type(f2(B())) # N: Revealed type is "__main__.B"
5840 reveal_type(f2(C())) # E: No overload variant of "f2" matches argument type "C" \
5841 # N: Possible overload variants: \
5842 # N: def f2(x: A) -> A \
5843 # N: def f2(x: B) -> B \
5844 # N: Revealed type is "Any"
5845
5846 @overload # E: Single overload definition, multiple required
5847 def f3(x: A) -> A: ...
5848 if maybe_true: # E: Condition can't be inferred, unable to merge overloads \
5849 # E: Name "maybe_true" is not defined
5850 @overload
5851 def f3(x: B) -> B: ...
5852 elif True:
5853 @overload
5854 def f3(x: C) -> C: ...
5855 else:
5856 @overload
5857 def f3(x: D) -> D: ...
5858 def f3(x): ...
5859 reveal_type(f3(A())) # N: Revealed type is "__main__.A"
5860 reveal_type(f3(B())) # E: No overload variant of "f3" matches argument type "B" \
5861 # N: Possible overload variant: \
5862 # N: def f3(x: A) -> A \
5863 # N: Revealed type is "Any"
5864
5865 @overload # E: Single overload definition, multiple required
5866 def f4(x: A) -> A: ...
5867 if maybe_true: # E: Condition can't be inferred, unable to merge overloads \
5868 # E: Name "maybe_true" is not defined
5869 @overload
5870 def f4(x: B) -> B: ...
5871 else:
5872 @overload
5873 def f4(x: D) -> D: ...
5874 def f4(x): ...
5875 reveal_type(f4(A())) # N: Revealed type is "__main__.A"
5876 reveal_type(f4(B())) # E: No overload variant of "f4" matches argument type "B" \
5877 # N: Possible overload variant: \
5878 # N: def f4(x: A) -> A \
5879 # N: Revealed type is "Any"
5880
5881
5882 [case testOverloadIfElse3]
5883 # flags: --always-false False
5884 from typing import overload
5885
5886 class A: ...
5887 class B: ...
5888 class C: ...
5889 class D: ...
5890 class E: ...
5891
5892 # -----
5893 # Match the first always-true block
5894 # Don't merge overloads if can't be certain about execution of block
5895 # -----
5896
5897 @overload
5898 def f1(x: A) -> A: ...
5899 if False:
5900 @overload
5901 def f1(x: B) -> B: ...
5902 else:
5903 @overload
5904 def f1(x: D) -> D: ...
5905 def f1(x): ...
5906 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
5907 reveal_type(f1(B())) # E: No overload variant of "f1" matches argument type "B" \
5908 # N: Possible overload variants: \
5909 # N: def f1(x: A) -> A \
5910 # N: def f1(x: D) -> D \
5911 # N: Revealed type is "Any"
5912 reveal_type(f1(D())) # N: Revealed type is "__main__.D"
5913
5914 @overload # E: Single overload definition, multiple required
5915 def f2(x: A) -> A: ...
5916 if False:
5917 @overload
5918 def f2(x: B) -> B: ...
5919 elif maybe_true: # E: Condition can't be inferred, unable to merge overloads \
5920 # E: Name "maybe_true" is not defined
5921 @overload
5922 def f2(x: C) -> C: ...
5923 else:
5924 @overload
5925 def f2(x: D) -> D: ...
5926 def f2(x): ...
5927 reveal_type(f2(A())) # N: Revealed type is "__main__.A"
5928 reveal_type(f2(C())) # E: No overload variant of "f2" matches argument type "C" \
5929 # N: Possible overload variant: \
5930 # N: def f2(x: A) -> A \
5931 # N: Revealed type is "Any"
5932
5933 @overload # E: Single overload definition, multiple required
5934 def f3(x: A) -> A: ...
5935 if maybe_true: # E: Condition can't be inferred, unable to merge overloads \
5936 # E: Name "maybe_true" is not defined
5937 @overload
5938 def f3(x: B) -> B: ...
5939 elif False:
5940 @overload
5941 def f3(x: C) -> C: ...
5942 else:
5943 @overload
5944 def f3(x: D) -> D: ...
5945 def f3(x): ...
5946 reveal_type(f3(A())) # N: Revealed type is "__main__.A"
5947 reveal_type(f3(B())) # E: No overload variant of "f3" matches argument type "B" \
5948 # N: Possible overload variant: \
5949 # N: def f3(x: A) -> A \
5950 # N: Revealed type is "Any"
5951
5952 def g(bool_var: bool) -> None:
5953 @overload
5954 def f4(x: A) -> A: ...
5955 if bool_var: # E: Condition can't be inferred, unable to merge overloads
5956 @overload
5957 def f4(x: B) -> B: ...
5958 elif maybe_true: # E: Name "maybe_true" is not defined
5959 # No 'Condition cannot be inferred' error here since it's already
5960 # emitted on the first condition, 'bool_var', above.
5961 @overload
5962 def f4(x: C) -> C: ...
5963 else:
5964 @overload
5965 def f4(x: D) -> D: ...
5966 @overload
5967 def f4(x: E) -> E: ...
5968 def f4(x): ...
5969 reveal_type(f4(E())) # N: Revealed type is "__main__.E"
5970 reveal_type(f4(B())) # E: No overload variant of "f4" matches argument type "B" \
5971 # N: Possible overload variants: \
5972 # N: def f4(x: A) -> A \
5973 # N: def f4(x: E) -> E \
5974 # N: Revealed type is "Any"
5975
5976
5977 [case testOverloadIfSkipUnknownExecution]
5978 # flags: --always-true True
5979 from typing import overload
5980
5981 class A: ...
5982 class B: ...
5983 class C: ...
5984 class D: ...
5985
5986 # -----
5987 # If blocks should be skipped if execution can't be certain
5988 # Overload name must match outer name
5989 # -----
5990
5991 @overload # E: Single overload definition, multiple required
5992 def f1(x: A) -> A: ...
5993 if maybe_true: # E: Condition can't be inferred, unable to merge overloads \
5994 # E: Name "maybe_true" is not defined
5995 @overload
5996 def f1(x: B) -> B: ...
5997 def f1(x): ...
5998 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
5999
6000 if maybe_true: # E: Condition can't be inferred, unable to merge overloads \
6001 # E: Name "maybe_true" is not defined
6002 @overload
6003 def f2(x: A) -> A: ...
6004 @overload
6005 def f2(x: B) -> B: ...
6006 @overload
6007 def f2(x: C) -> C: ...
6008 def f2(x): ...
6009 reveal_type(f2(A())) # E: No overload variant of "f2" matches argument type "A" \
6010 # N: Possible overload variants: \
6011 # N: def f2(x: B) -> B \
6012 # N: def f2(x: C) -> C \
6013 # N: Revealed type is "Any"
6014
6015 if True:
6016 @overload # E: Single overload definition, multiple required
6017 def f3(x: A) -> A: ...
6018 if maybe_true: # E: Condition can't be inferred, unable to merge overloads \
6019 # E: Name "maybe_true" is not defined
6020 @overload
6021 def f3(x: B) -> B: ...
6022 def f3(x): ...
6023 reveal_type(f3(A())) # N: Revealed type is "__main__.A"
6024
6025 if True:
6026 if maybe_true: # E: Condition can't be inferred, unable to merge overloads \
6027 # E: Name "maybe_true" is not defined
6028 @overload
6029 def f4(x: A) -> A: ...
6030 @overload
6031 def f4(x: B) -> B: ...
6032 @overload
6033 def f4(x: C) -> C: ...
6034 def f4(x): ...
6035 reveal_type(f4(A())) # E: No overload variant of "f4" matches argument type "A" \
6036 # N: Possible overload variants: \
6037 # N: def f4(x: B) -> B \
6038 # N: def f4(x: C) -> C \
6039 # N: Revealed type is "Any"
6040
6041 [case testOverloadIfDontSkipUnrelatedOverload]
6042 # flags: --always-true True
6043 from typing import overload
6044
6045 class A: ...
6046 class B: ...
6047 class C: ...
6048 class D: ...
6049
6050 # -----
6051 # Don't skip if block if overload name doesn't match outer name
6052 # -----
6053
6054 @overload # E: Single overload definition, multiple required
6055 def f1(x: A) -> A: ...
6056 if maybe_true: # E: Name "maybe_true" is not defined
6057 @overload # E: Single overload definition, multiple required
6058 def g1(x: B) -> B: ...
6059 def f1(x): ... # E: Name "f1" already defined on line 13
6060 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
6061
6062 if maybe_true: # E: Name "maybe_true" is not defined
6063 @overload # E: Single overload definition, multiple required
6064 def g2(x: A) -> A: ...
6065 @overload
6066 def f2(x: B) -> B: ...
6067 @overload
6068 def f2(x: C) -> C: ...
6069 def f2(x): ...
6070 reveal_type(f2(A())) # E: No overload variant of "f2" matches argument type "A" \
6071 # N: Possible overload variants: \
6072 # N: def f2(x: B) -> B \
6073 # N: def f2(x: C) -> C \
6074 # N: Revealed type is "Any"
6075
6076 if True:
6077 @overload # E: Single overload definition, multiple required
6078 def f3(x: A) -> A: ...
6079 def f3(x): ...
6080 if maybe_true: # E: Name "maybe_true" is not defined
6081 @overload # E: Single overload definition, multiple required
6082 def g3(x: B) -> B: ...
6083 reveal_type(f3(A())) # N: Revealed type is "__main__.A"
6084
6085 if True:
6086 if maybe_true: # E: Name "maybe_true" is not defined
6087 @overload # E: Single overload definition, multiple required
6088 def g4(x: A) -> A: ...
6089 @overload
6090 def f4(x: B) -> B: ...
6091 @overload
6092 def f4(x: C) -> C: ...
6093 def f4(x): ...
6094 reveal_type(f4(A())) # E: No overload variant of "f4" matches argument type "A" \
6095 # N: Possible overload variants: \
6096 # N: def f4(x: B) -> B \
6097 # N: def f4(x: C) -> C \
6098 # N: Revealed type is "Any"
6099
6100 [case testOverloadIfNotMergingDifferentNames]
6101 # flags: --always-true True
6102 from typing import overload
6103
6104 class A: ...
6105 class B: ...
6106 class C: ...
6107 class D: ...
6108
6109 # -----
6110 # Don't merge overloads if IfStmts contains overload with different name
6111 # -----
6112
6113 @overload # E: An overloaded function outside a stub file must have an implementation
6114 def f1(x: A) -> A: ...
6115 @overload
6116 def f1(x: B) -> B: ...
6117 if True:
6118 @overload # E: Single overload definition, multiple required
6119 def g1(x: C) -> C: ...
6120 def f1(x): ... # E: Name "f1" already defined on line 13
6121 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
6122 reveal_type(f1(C())) # E: No overload variant of "f1" matches argument type "C" \
6123 # N: Possible overload variants: \
6124 # N: def f1(x: A) -> A \
6125 # N: def f1(x: B) -> B \
6126 # N: Revealed type is "Any"
6127
6128 if True:
6129 @overload # E: Single overload definition, multiple required
6130 def g2(x: A) -> A: ...
6131 @overload
6132 def f2(x: B) -> B: ...
6133 @overload
6134 def f2(x: C) -> C: ...
6135 def f2(x): ...
6136 reveal_type(f2(A())) # E: No overload variant of "f2" matches argument type "A" \
6137 # N: Possible overload variants: \
6138 # N: def f2(x: B) -> B \
6139 # N: def f2(x: C) -> C \
6140 # N: Revealed type is "Any"
6141 reveal_type(f2(B())) # N: Revealed type is "__main__.B"
6142
6143 if True:
6144 if True:
6145 @overload # E: Single overload definition, multiple required
6146 def g3(x: A) -> A: ...
6147 @overload
6148 def f3(x: B) -> B: ...
6149 @overload
6150 def f3(x: C) -> C: ...
6151 def f3(x): ...
6152 reveal_type(f3(A())) # E: No overload variant of "f3" matches argument type "A" \
6153 # N: Possible overload variants: \
6154 # N: def f3(x: B) -> B \
6155 # N: def f3(x: C) -> C \
6156 # N: Revealed type is "Any"
6157 reveal_type(f3(B())) # N: Revealed type is "__main__.B"
6158
6159 [case testOverloadIfSplitFunctionDef_no_native_parse]
6160 # flags: --always-true True --always-false False
6161 from typing import overload
6162
6163 class A: ...
6164 class B: ...
6165 class C: ...
6166 class D: ...
6167
6168 # -----
6169 # Test split FuncDefs
6170 # -----
6171
6172 @overload
6173 def f1(x: A) -> A: ...
6174 @overload
6175 def f1(x: B) -> B: ...
6176 if True:
6177 def f1(x): ...
6178 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
6179
6180 @overload
6181 def f2(x: A) -> A: ...
6182 @overload
6183 def f2(x: B) -> B: ...
6184 if False:
6185 def f2(x): ...
6186 else:
6187 def f2(x): ...
6188 reveal_type(f2(A())) # N: Revealed type is "__main__.A"
6189
6190 @overload # E: An overloaded function outside a stub file must have an implementation
6191 def f3(x: A) -> A: ...
6192 @overload
6193 def f3(x: B) -> B: ...
6194 if True:
6195 def f3(x): ... # E: Name "f3" already defined on line 31
6196 else:
6197 pass # some other node
6198 def f3(x): ...
6199 reveal_type(f3(A())) # N: Revealed type is "__main__.A"
6200
6201 [case testOverloadIfMixed]
6202 # flags: --always-true True --always-false False
6203 from typing import overload, TYPE_CHECKING
6204
6205 class A: ...
6206 class B: ...
6207 class C: ...
6208 class D: ...
6209
6210 if maybe_var: # E: Name "maybe_var" is not defined
6211 pass
6212 if True:
6213 @overload
6214 def f1(x: A) -> A: ...
6215 @overload
6216 def f1(x: B) -> B: ...
6217 def f1(x): ...
6218 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
6219 reveal_type(f1(B())) # N: Revealed type is "__main__.B"
6220
6221 if True:
6222 @overload
6223 def f2(x: A) -> A: ...
6224 @overload
6225 def f2(x: B) -> B: ...
6226 def f2(x): ...
6227 reveal_type(f2(A())) # N: Revealed type is "__main__.A"
6228 reveal_type(f2(B())) # N: Revealed type is "__main__.B"
6229
6230 if True:
6231 @overload
6232 def f3(x: A) -> A: ...
6233 @overload
6234 def f3(x: B) -> B: ...
6235 def f3(x): ...
6236 reveal_type(f3(A())) # N: Revealed type is "__main__.A"
6237 reveal_type(f3(B())) # N: Revealed type is "__main__.B"
6238
6239 # Don't crash with AssignmentStmt if elif
6240 @overload # E: Single overload definition, multiple required
6241 def f4(x: A) -> A: ...
6242 if False:
6243 @overload
6244 def f4(x: B) -> B: ...
6245 elif True:
6246 var = 1
6247 def f4(x): ... # E: Name "f4" already defined on line 39
6248
6249 if TYPE_CHECKING:
6250 @overload
6251 def f5(x: A) -> A: ...
6252 @overload
6253 def f5(x: B) -> B: ...
6254 def f5(x): ...
6255 reveal_type(f5(A())) # N: Revealed type is "__main__.A"
6256 reveal_type(f5(B())) # N: Revealed type is "__main__.B"
6257
6258 # Test from check-functions - testUnconditionalRedefinitionOfConditionalFunction
6259 # Don't merge If blocks if they appear before any overloads
6260 # and don't contain any overloads themselves.
6261 if maybe_true: # E: Name "maybe_true" is not defined
6262 def f6(x): ...
6263 def f6(x): ... # E: Name "f6" already defined on line 61
6264
6265 if maybe_true: # E: Name "maybe_true" is not defined
6266 pass # Some other node
6267 def f7(x): ...
6268 def f7(x): ... # E: Name "f7" already defined on line 66
6269
6270 @overload
6271 def f8(x: A) -> A: ...
6272 @overload
6273 def f8(x: B) -> B: ...
6274 if False:
6275 def f8(x: C) -> C: ...
6276 def f8(x): ...
6277 reveal_type(f8(A())) # N: Revealed type is "__main__.A"
6278 reveal_type(f8(C())) # E: No overload variant of "f8" matches argument type "C" \
6279 # N: Possible overload variants: \
6280 # N: def f8(x: A) -> A \
6281 # N: def f8(x: B) -> B \
6282 # N: Revealed type is "Any"
6283
6284 if maybe_true: # E: Condition can't be inferred, unable to merge overloads \
6285 # E: Name "maybe_true" is not defined
6286 @overload
6287 def f9(x: A) -> A: ...
6288 if another_maybe_true: # E: Condition can't be inferred, unable to merge overloads \
6289 # E: Name "another_maybe_true" is not defined
6290 @overload
6291 def f9(x: B) -> B: ...
6292 @overload
6293 def f9(x: C) -> C: ...
6294 @overload
6295 def f9(x: D) -> D: ...
6296 def f9(x): ...
6297 reveal_type(f9(A())) # E: No overload variant of "f9" matches argument type "A" \
6298 # N: Possible overload variants: \
6299 # N: def f9(x: C) -> C \
6300 # N: def f9(x: D) -> D \
6301 # N: Revealed type is "Any"
6302 reveal_type(f9(C())) # N: Revealed type is "__main__.C"
6303
6304 if True:
6305 if maybe_true: # E: Condition can't be inferred, unable to merge overloads \
6306 # E: Name "maybe_true" is not defined
6307 @overload
6308 def f10(x: A) -> A: ...
6309 if another_maybe_true: # E: Condition can't be inferred, unable to merge overloads \
6310 # E: Name "another_maybe_true" is not defined
6311 @overload
6312 def f10(x: B) -> B: ...
6313 @overload
6314 def f10(x: C) -> C: ...
6315 @overload
6316 def f10(x: D) -> D: ...
6317 def f10(x): ...
6318 reveal_type(f10(A())) # E: No overload variant of "f10" matches argument type "A" \
6319 # N: Possible overload variants: \
6320 # N: def f10(x: C) -> C \
6321 # N: def f10(x: D) -> D \
6322 # N: Revealed type is "Any"
6323 reveal_type(f10(C())) # N: Revealed type is "__main__.C"
6324
6325 if some_var: # E: Name "some_var" is not defined
6326 pass
6327 @overload
6328 def f11(x: A) -> A: ...
6329 @overload
6330 def f11(x: B) -> B: ...
6331 def f11(x): ...
6332 reveal_type(f11(A())) # N: Revealed type is "__main__.A"
6333
6334 if True:
6335 if some_var: # E: Name "some_var" is not defined
6336 pass
6337 @overload
6338 def f12(x: A) -> A: ...
6339 @overload
6340 def f12(x: B) -> B: ...
6341 def f12(x): ...
6342 reveal_type(f12(A())) # N: Revealed type is "__main__.A"
6343
6344 [typing fixtures/typing-medium.pyi]
6345
6346 [case testAdjacentConditionalOverloads]
6347 # flags: --always-true true_alias
6348 from typing import overload
6349
6350 true_alias = True
6351
6352 if true_alias:
6353 @overload
6354 def ham(v: str) -> list[str]: ...
6355
6356 @overload
6357 def ham(v: int) -> list[int]: ...
6358
6359 def ham(v: "int | str") -> "list[str] | list[int]":
6360 return []
6361
6362 if true_alias:
6363 @overload
6364 def spam(v: str) -> str: ...
6365
6366 @overload
6367 def spam(v: int) -> int: ...
6368
6369 def spam(v: "int | str") -> "str | int":
6370 return ""
6371
6372 reveal_type(ham) # N: Revealed type is "Overload(def (v: builtins.str) -> builtins.list[builtins.str], def (v: builtins.int) -> builtins.list[builtins.int])"
6373 reveal_type(spam) # N: Revealed type is "Overload(def (v: builtins.str) -> builtins.str, def (v: builtins.int) -> builtins.int)"
6374
6375 reveal_type(ham("")) # N: Revealed type is "builtins.list[builtins.str]"
6376 reveal_type(ham(0)) # N: Revealed type is "builtins.list[builtins.int]"
6377 reveal_type(spam("")) # N: Revealed type is "builtins.str"
6378 reveal_type(spam(0)) # N: Revealed type is "builtins.int"
6379
6380 [case testOverloadIfUnconditionalFuncDef]
6381 # flags: --always-true True --always-false False
6382 from typing import overload
6383
6384 class A: ...
6385 class B: ...
6386
6387 # -----
6388 # Don't merge conditional FuncDef after unconditional one
6389 # -----
6390
6391 @overload
6392 def f1(x: A) -> A: ...
6393 @overload
6394 def f1(x: B) -> B: ...
6395 def f1(x): ...
6396
6397 @overload
6398 def f2(x: A) -> A: ...
6399 if True:
6400 @overload
6401 def f2(x: B) -> B: ...
6402 def f2(x): ...
6403 if True:
6404 def f2(x): ... # E: Name "f2" already defined on line 17
6405
6406 [case testOverloadItemHasMoreGeneralReturnType]
6407 from typing import overload
6408
6409 @overload
6410 def f() -> object: ...
6411
6412 @overload
6413 def f(x: int) -> object: ...
6414
6415 def f(x: int = 0) -> int:
6416 return x
6417
6418 @overload
6419 def g() -> object: ...
6420
6421 @overload
6422 def g(x: int) -> str: ...
6423
6424 def g(x: int = 0) -> int: # E: Overloaded function implementation cannot produce return type of signature 2
6425 return x
6426
6427 [case testOverloadIfNestedOk]
6428 # flags: --always-true True --always-false False
6429 from typing import overload
6430
6431 class A: ...
6432 class B: ...
6433 class C: ...
6434 class D: ...
6435
6436 @overload
6437 def f1(g: A) -> A: ...
6438 if True:
6439 @overload
6440 def f1(g: B) -> B: ...
6441 if True:
6442 @overload
6443 def f1(g: C) -> C: ...
6444 @overload
6445 def f1(g: D) -> D: ...
6446 def f1(g): ...
6447 reveal_type(f1(A())) # N: Revealed type is "__main__.A"
6448 reveal_type(f1(B())) # N: Revealed type is "__main__.B"
6449 reveal_type(f1(C())) # N: Revealed type is "__main__.C"
6450 reveal_type(f1(D())) # N: Revealed type is "__main__.D"
6451
6452 @overload
6453 def f2(g: A) -> A: ...
6454 if True:
6455 @overload
6456 def f2(g: B) -> B: ...
6457 if True:
6458 @overload
6459 def f2(g: C) -> C: ...
6460 if True:
6461 @overload
6462 def f2(g: D) -> D: ...
6463 def f2(g): ...
6464 reveal_type(f2(A())) # N: Revealed type is "__main__.A"
6465 reveal_type(f2(B())) # N: Revealed type is "__main__.B"
6466 reveal_type(f2(C())) # N: Revealed type is "__main__.C"
6467 reveal_type(f2(D())) # N: Revealed type is "__main__.D"
6468
6469 @overload
6470 def f3(g: A) -> A: ...
6471 if True:
6472 if True:
6473 @overload
6474 def f3(g: B) -> B: ...
6475 if True:
6476 @overload
6477 def f3(g: C) -> C: ...
6478 def f3(g): ...
6479 reveal_type(f3(A())) # N: Revealed type is "__main__.A"
6480 reveal_type(f3(B())) # N: Revealed type is "__main__.B"
6481 reveal_type(f3(C())) # N: Revealed type is "__main__.C"
6482
6483 @overload
6484 def f4(g: A) -> A: ...
6485 if True:
6486 if False:
6487 @overload
6488 def f4(g: B) -> B: ...
6489 else:
6490 @overload
6491 def f4(g: C) -> C: ...
6492 def f4(g): ...
6493 reveal_type(f4(A())) # N: Revealed type is "__main__.A"
6494 reveal_type(f4(B())) # E: No overload variant of "f4" matches argument type "B" \
6495 # N: Possible overload variants: \
6496 # N: def f4(g: A) -> A \
6497 # N: def f4(g: C) -> C \
6498 # N: Revealed type is "Any"
6499 reveal_type(f4(C())) # N: Revealed type is "__main__.C"
6500
6501 @overload
6502 def f5(g: A) -> A: ...
6503 if True:
6504 if False:
6505 @overload
6506 def f5(g: B) -> B: ...
6507 elif True:
6508 @overload
6509 def f5(g: C) -> C: ...
6510 def f5(g): ...
6511 reveal_type(f5(A())) # N: Revealed type is "__main__.A"
6512 reveal_type(f5(B())) # E: No overload variant of "f5" matches argument type "B" \
6513 # N: Possible overload variants: \
6514 # N: def f5(g: A) -> A \
6515 # N: def f5(g: C) -> C \
6516 # N: Revealed type is "Any"
6517 reveal_type(f5(C())) # N: Revealed type is "__main__.C"
6518
6519 [case testOverloadIfNestedFailure]
6520 # flags: --always-true True --always-false False
6521 from typing import overload
6522
6523 class A: ...
6524 class B: ...
6525 class C: ...
6526 class D: ...
6527
6528 @overload # E: Single overload definition, multiple required
6529 def f1(g: A) -> A: ...
6530 if True:
6531 @overload # E: Single overload definition, multiple required
6532 def f1(g: B) -> B: ... # E: Incompatible redefinition (redefinition with type "Callable[[B], B]", original type "Callable[[A], A]")
6533 if maybe_true: # E: Condition can't be inferred, unable to merge overloads \
6534 # E: Name "maybe_true" is not defined
6535 @overload
6536 def f1(g: C) -> C: ...
6537 @overload
6538 def f1(g: D) -> D: ...
6539 def f1(g): ... # E: Name "f1" already defined on line 9
6540
6541 @overload # E: Single overload definition, multiple required
6542 def f2(g: A) -> A: ...
6543 if True:
6544 if False:
6545 @overload
6546 def f2(g: B) -> B: ...
6547 elif maybe_true: # E: Name "maybe_true" is not defined
6548 @overload # E: Single overload definition, multiple required
6549 def f2(g: C) -> C: ... # E: Incompatible redefinition (redefinition with type "Callable[[C], C]", original type "Callable[[A], A]")
6550 def f2(g): ... # E: Name "f2" already defined on line 21
6551
6552 @overload # E: Single overload definition, multiple required
6553 def f3(g: A) -> A: ...
6554 if True:
6555 @overload # E: Single overload definition, multiple required
6556 def f3(g: B) -> B: ... # E: Incompatible redefinition (redefinition with type "Callable[[B], B]", original type "Callable[[A], A]")
6557 if True:
6558 pass # Some other node
6559 @overload # E: Name "f3" already defined on line 32 \
6560 # E: An overloaded function outside a stub file must have an implementation
6561 def f3(g: C) -> C: ...
6562 @overload
6563 def f3(g: D) -> D: ...
6564 def f3(g): ... # E: Name "f3" already defined on line 32
6565
6566 [case testOverloadingWithParamSpec]
6567 from typing import TypeVar, Callable, Any, overload
6568 from typing_extensions import ParamSpec, Concatenate
6569
6570 P = ParamSpec("P")
6571 R = TypeVar("R")
6572
6573 @overload
6574 def func(x: Callable[Concatenate[Any, P], R]) -> Callable[P, R]: ...
6575 @overload
6576 def func(x: Callable[P, R]) -> Callable[Concatenate[str, P], R]: ...
6577 def func(x: Callable[..., R]) -> Callable[..., R]: ...
6578
6579 def foo(arg1: str, arg2: int) -> bytes: ...
6580 reveal_type(func(foo)) # N: Revealed type is "def (arg2: builtins.int) -> builtins.bytes"
6581
6582 def bar() -> int: ...
6583 reveal_type(func(bar)) # N: Revealed type is "def (builtins.str) -> builtins.int"
6584
6585 baz: Callable[[str, str], str] = lambda x, y: 'baz'
6586 reveal_type(func(baz)) # N: Revealed type is "def (builtins.str) -> builtins.str"
6587
6588 eggs = lambda: 'eggs'
6589 reveal_type(func(eggs)) # N: Revealed type is "def (builtins.str) -> builtins.str"
6590
6591 spam: Callable[..., str] = lambda x, y: 'baz'
6592 reveal_type(func(spam)) # N: Revealed type is "def (*Any, **Any) -> Any"
6593 [builtins fixtures/paramspec.pyi]
6594
6595 [case testGenericOverloadOverlapWithType]
6596 import m
6597
6598 [file m.pyi]
6599 from typing import TypeVar, Type, overload, Callable
6600
6601 T = TypeVar("T", bound=str)
6602 @overload
6603 def foo(x: Type[T] | int) -> int: ...
6604 @overload
6605 def foo(x: Callable[[int], bool]) -> str: ...
6606
6607 [case testGenericOverloadOverlapWithCollection]
6608 import m
6609
6610 [file m.pyi]
6611 from typing import TypeVar, Sequence, overload, List
6612
6613 T = TypeVar("T", bound=str)
6614
6615 @overload
6616 def foo(x: List[T]) -> str: ...
6617 @overload
6618 def foo(x: Sequence[int]) -> int: ...
6619 [builtins fixtures/list.pyi]
6620
6621 # Also see `check-python38.test` for similar tests with `/` args:
6622 [case testOverloadPositionalOnlyErrorMessageOldStyle]
6623 from typing import overload
6624
6625 @overload
6626 def foo(__a: int): ...
6627 @overload
6628 def foo(a: str): ...
6629 def foo(a): ...
6630
6631 foo(a=1)
6632 [out]
6633 main:9: error: No overload variant of "foo" matches argument type "int"
6634 main:9: note: Possible overload variants:
6635 main:9: note: def foo(int, /) -> Any
6636 main:9: note: def foo(a: str) -> Any
6637
6638 [case testOverloadUnionGenericBounds]
6639 from typing import overload, TypeVar, Sequence, Union
6640
6641 class Entity: ...
6642 class Assoc: ...
6643
6644 E = TypeVar("E", bound=Entity)
6645 A = TypeVar("A", bound=Assoc)
6646
6647 class Test:
6648 @overload
6649 def foo(self, arg: Sequence[E]) -> None: ...
6650 @overload
6651 def foo(self, arg: Sequence[A]) -> None: ...
6652 def foo(self, arg: Union[Sequence[E], Sequence[A]]) -> None:
6653 ...
6654
6655 [case testOverloadedStaticMethodOnInstance]
6656 from typing import overload
6657
6658 class Snafu(object):
6659 @overload
6660 @staticmethod
6661 def snafu(value: bytes) -> bytes: ...
6662 @overload
6663 @staticmethod
6664 def snafu(value: str) -> str: ...
6665 @staticmethod
6666 def snafu(value):
6667 ...
6668 reveal_type(Snafu().snafu('123')) # N: Revealed type is "builtins.str"
6669 reveal_type(Snafu.snafu('123')) # N: Revealed type is "builtins.str"
6670 [builtins fixtures/staticmethod.pyi]
6671
6672 [case testOverloadedWithInternalTypeVars]
6673 import m
6674
6675 [file m.pyi]
6676 from typing import Callable, TypeVar, overload
6677
6678 T = TypeVar("T")
6679 S = TypeVar("S", bound=str)
6680
6681 @overload
6682 def foo(x: int = ...) -> Callable[[T], T]: ...
6683 @overload
6684 def foo(x: S = ...) -> Callable[[T], T]: ...
6685
6686 [case testOverloadGenericStarArgOverlap]
6687 from typing import Any, Callable, TypeVar, overload, Union, Tuple, List
6688
6689 F = TypeVar("F", bound=Callable[..., Any])
6690 S = TypeVar("S", bound=int)
6691
6692 def id(f: F) -> F: ...
6693
6694 @overload
6695 def struct(*cols: S) -> int: ...
6696 @overload
6697 def struct(__cols: Union[List[S], Tuple[S, ...]]) -> int: ...
6698 @id
6699 def struct(*cols: Union[S, Union[List[S], Tuple[S, ...]]]) -> int:
6700 pass
6701 [builtins fixtures/tuple.pyi]
6702
6703 [case testRegularGenericDecoratorOverload]
6704 from typing import Callable, overload, TypeVar, List
6705
6706 S = TypeVar("S")
6707 T = TypeVar("T")
6708 def transform(func: Callable[[S], List[T]]) -> Callable[[S], T]: ...
6709
6710 @overload
6711 def foo(x: int) -> List[float]: ...
6712 @overload
6713 def foo(x: str) -> List[str]: ...
6714 def foo(x): ...
6715
6716 reveal_type(transform(foo)) # N: Revealed type is "Overload(def (builtins.int) -> builtins.float, def (builtins.str) -> builtins.str)"
6717
6718 @transform
6719 @overload
6720 def bar(x: int) -> List[float]: ...
6721 @transform
6722 @overload
6723 def bar(x: str) -> List[str]: ...
6724 @transform
6725 def bar(x): ...
6726
6727 reveal_type(bar) # N: Revealed type is "Overload(def (builtins.int) -> builtins.float, def (builtins.str) -> builtins.str)"
6728 [builtins fixtures/paramspec.pyi]
6729
6730 [case testOverloadOverlapWithNameOnlyArgs]
6731 from typing import overload
6732
6733 @overload
6734 def d(x: int) -> int: ...
6735 @overload
6736 def d(f: int, *, x: int) -> str: ...
6737 def d(*args, **kwargs): ...
6738 [builtins fixtures/tuple.pyi]
6739
6740 [case testOverloadCallableGenericSelf]
6741 from typing import Any, TypeVar, Generic, overload, reveal_type
6742
6743 T = TypeVar("T")
6744
6745 class MyCallable(Generic[T]):
6746 def __init__(self, t: T):
6747 self.t = t
6748
6749 @overload
6750 def __call__(self: "MyCallable[int]") -> str: ...
6751 @overload
6752 def __call__(self: "MyCallable[str]") -> int: ...
6753 def __call__(self): ...
6754
6755 c = MyCallable(5)
6756 reveal_type(c) # N: Revealed type is "__main__.MyCallable[builtins.int]"
6757 reveal_type(c()) # N: Revealed type is "builtins.str"
6758
6759 c2 = MyCallable("test")
6760 reveal_type(c2) # N: Revealed type is "__main__.MyCallable[builtins.str]"
6761 reveal_type(c2()) # should be int # N: Revealed type is "builtins.int"
6762 [builtins fixtures/tuple.pyi]
6763
6764 [case testOverloadWithStarAnyFallback]
6765 from typing import overload, Any
6766
6767 class A:
6768 @overload
6769 def f(self, e: str) -> str: ...
6770 @overload
6771 def f(self, *args: Any, **kwargs: Any) -> Any: ...
6772 def f(self, *args, **kwargs):
6773 pass
6774
6775 class B:
6776 @overload
6777 def f(self, e: str, **kwargs: Any) -> str: ...
6778 @overload
6779 def f(self, *args: Any, **kwargs: Any) -> Any: ...
6780 def f(self, *args, **kwargs):
6781 pass
6782 [builtins fixtures/tuple.pyi]
6783
6784 [case testOverloadsSafeOverlapAllowed]
6785 from lib import *
6786 [file lib.pyi]
6787 from typing import overload
6788
6789 @overload
6790 def bar(x: object) -> object: ...
6791 @overload
6792 def bar(x: int = ...) -> int: ...
6793
6794 [case testOverloadsInvariantOverlapAllowed]
6795 from lib import *
6796 [file lib.pyi]
6797 from typing import overload, List
6798
6799 @overload
6800 def bar(x: List[int]) -> List[int]: ...
6801 @overload
6802 def bar(x: List[object]) -> List[object]: ...
6803
6804 [case testOverloadsNoneAnyOverlapAllowed]
6805 from lib import *
6806 [file lib.pyi]
6807 from typing import overload, Any
6808
6809 @overload
6810 def foo(x: None) -> int: ...
6811 @overload
6812 def foo(x: object) -> str: ...
6813
6814 @overload
6815 def bar(x: int) -> int: ...
6816 @overload
6817 def bar(x: Any) -> str: ...
6818
6819 [case testOverloadOnInvalidTypeArgument]
6820 from typing import TypeVar, Self, Generic, overload
6821
6822 class C: pass
6823
6824 T = TypeVar("T", bound=C)
6825
6826 class D(Generic[T]):
6827 @overload
6828 def f(self, x: int) -> int: ...
6829 @overload
6830 def f(self, x: str) -> str: ...
6831 def f(Self, x): ...
6832
6833 a: D[str] # E: Type argument "str" of "D" must be a subtype of "C"
6834 reveal_type(a.f(1)) # N: Revealed type is "builtins.int"
6835 reveal_type(a.f("x")) # N: Revealed type is "builtins.str"
6836
6837 [case testMultiAssignFromUnionInOverloadCached]
6838 from typing import Iterable, overload, Union, Optional
6839
6840 @overload
6841 def always_bytes(str_or_bytes: None) -> None: ...
6842 @overload
6843 def always_bytes(str_or_bytes: Union[str, bytes]) -> bytes: ...
6844 def always_bytes(str_or_bytes: Union[None, str, bytes]) -> Optional[bytes]:
6845 pass
6846
6847 class Headers:
6848 def __init__(self, iter: Iterable[tuple[bytes, bytes]]) -> None: ...
6849
6850 headers: Union[Headers, dict[Union[str, bytes], Union[str, bytes]], Iterable[tuple[bytes, bytes]]]
6851
6852 if isinstance(headers, dict):
6853 headers = Headers(
6854 (always_bytes(k), always_bytes(v)) for k, v in headers.items()
6855 )
6856
6857 reveal_type(headers) # N: Revealed type is "__main__.Headers | typing.Iterable[tuple[builtins.bytes, builtins.bytes]]"
6858 [builtins fixtures/isinstancelist.pyi]