Debian Codegraph @

test-data/unit/check-protocols.test

raw
1 -- Simple protocol types
2 -- ---------------------
3
4 [case testCannotInstantiateProtocol]
5 from typing import Protocol
6
7 class P(Protocol):
8 def meth(self) -> None:
9 pass
10
11 P() # E: Cannot instantiate protocol class "P"
12
13 [case testSimpleProtocolOneMethod]
14 from typing import Protocol
15
16 class P(Protocol):
17 def meth(self) -> None:
18 pass
19
20 class B: pass
21 class C:
22 def meth(self) -> None:
23 pass
24
25 x: P
26 def fun(x: P) -> None:
27 x.meth()
28 x.meth(x) # E: Too many arguments for "meth" of "P"
29 x.bad # E: "P" has no attribute "bad"
30
31 x = C()
32 x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "P")
33
34 fun(C())
35 fun(B()) # E: Argument 1 to "fun" has incompatible type "B"; expected "P"
36
37 def fun2() -> P:
38 return C()
39 def fun3() -> P:
40 return B() # E: Incompatible return value type (got "B", expected "P")
41
42 [case testProtocolAttrAccessDecoratedGetAttrDunder]
43 from typing import Any, Protocol, Callable
44
45 def typed_decorator(fun: Callable) -> Callable[[Any, str], str]:
46 pass
47
48 def untyped_decorator(fun):
49 pass
50
51 class P(Protocol):
52 @property
53 def x(self) -> int:
54 pass
55
56 class A:
57 @untyped_decorator
58 def __getattr__(self, key: str) -> int:
59 pass
60
61 class B:
62 @typed_decorator
63 def __getattr__(self, key: str) -> int:
64 pass
65
66 class C:
67 def __getattr__(self, key: str) -> int:
68 pass
69
70 def fun(x: P) -> None:
71 pass
72
73 a: A
74 reveal_type(a.x)
75 fun(a)
76
77 b: B
78 reveal_type(b.x)
79 fun(b)
80
81 c: C
82 reveal_type(c.x)
83 fun(c)
84 [out]
85 main:32: note: Revealed type is "Any"
86 main:36: note: Revealed type is "builtins.str"
87 main:37: error: Argument 1 to "fun" has incompatible type "B"; expected "P"
88 main:37: note: Following member(s) of "B" have conflicts:
89 main:37: note: x: expected "int", got "str"
90 main:40: note: Revealed type is "builtins.int"
91 [builtins fixtures/bool.pyi]
92
93 [case testSimpleProtocolOneAbstractMethod]
94 from typing import Protocol
95 from abc import abstractmethod
96
97 class P(Protocol):
98 @abstractmethod
99 def meth(self) -> None:
100 pass
101
102 class B: pass
103 class C:
104 def meth(self) -> None:
105 pass
106 class D(B):
107 def meth(self) -> None:
108 pass
109
110 x: P
111 def fun(x: P) -> None:
112 x.meth()
113 x.meth(x) # E: Too many arguments for "meth" of "P"
114 x.bad # E: "P" has no attribute "bad"
115
116 x = C()
117 x = D()
118 x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "P")
119 fun(C())
120 fun(D())
121 fun(B()) # E: Argument 1 to "fun" has incompatible type "B"; expected "P"
122 fun(x)
123
124 [case testProtocolMethodBodies]
125 from typing import Protocol, List
126
127 class P(Protocol):
128 def meth(self) -> int:
129 return 'no way' # E: Incompatible return value type (got "str", expected "int")
130
131 # explicit ellipsis is OK in protocol methods
132 class P2(Protocol):
133 def meth2(self) -> List[int]:
134 ...
135 [builtins fixtures/list.pyi]
136
137 [case testSimpleProtocolOneMethodOverride]
138 from typing import Protocol, Union
139
140 class P(Protocol):
141 def meth(self) -> Union[int, str]:
142 pass
143 class SubP(P, Protocol):
144 def meth(self) -> int:
145 pass
146
147 class B: pass
148 class C:
149 def meth(self) -> int:
150 pass
151 z: P
152 x: SubP
153 def fun(x: SubP) -> str:
154 x.bad # E: "SubP" has no attribute "bad"
155 return x.meth() # E: Incompatible return value type (got "int", expected "str")
156
157 z = x
158 x = C()
159 x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "SubP")
160
161 reveal_type(fun(C())) # N: Revealed type is "builtins.str"
162 fun(B()) # E: Argument 1 to "fun" has incompatible type "B"; expected "SubP"
163
164 [case testSimpleProtocolTwoMethodsMerge]
165 from typing import Protocol
166
167 class P1(Protocol):
168 def meth1(self) -> int:
169 pass
170 class P2(Protocol):
171 def meth2(self) -> str:
172 pass
173 class P(P1, P2, Protocol): pass
174
175 class B: pass
176 class C1:
177 def meth1(self) -> int:
178 pass
179 class C2(C1):
180 def meth2(self) -> str:
181 pass
182 class C:
183 def meth1(self) -> int:
184 pass
185 def meth2(self) -> str:
186 pass
187
188 class AnotherP(Protocol):
189 def meth1(self) -> int:
190 pass
191 def meth2(self) -> str:
192 pass
193
194 x: P
195 reveal_type(x.meth1()) # N: Revealed type is "builtins.int"
196 reveal_type(x.meth2()) # N: Revealed type is "builtins.str"
197
198 c: C
199 c1: C1
200 c2: C2
201 y: AnotherP
202
203 if int():
204 x = c
205 if int():
206 x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "P")
207 if int():
208 x = c1 # E: Incompatible types in assignment (expression has type "C1", variable has type "P") \
209 # N: "C1" is missing following "P" protocol member: \
210 # N: meth2
211 if int():
212 x = c2
213 if int():
214 x = y
215 if int():
216 y = x
217
218 [case testSimpleProtocolTwoMethodsExtend]
219 from typing import Protocol
220
221 class P1(Protocol):
222 def meth1(self) -> int:
223 pass
224 class P2(P1, Protocol):
225 def meth2(self) -> str:
226 pass
227
228 class Cbad:
229 def meth1(self) -> int:
230 pass
231
232 class C:
233 def meth1(self) -> int:
234 pass
235 def meth2(self) -> str:
236 pass
237
238 x: P2
239 reveal_type(x.meth1()) # N: Revealed type is "builtins.int"
240 reveal_type(x.meth2()) # N: Revealed type is "builtins.str"
241
242 if int():
243 x = C() # OK
244 if int():
245 x = Cbad() # E: Incompatible types in assignment (expression has type "Cbad", variable has type "P2") \
246 # N: "Cbad" is missing following "P2" protocol member: \
247 # N: meth2
248
249 [case testProtocolMethodVsAttributeErrors]
250 from typing import Protocol
251
252 class P(Protocol):
253 def meth(self) -> int:
254 pass
255 class C:
256 meth: int
257 x: P = C() # E: Incompatible types in assignment (expression has type "C", variable has type "P") \
258 # N: Following member(s) of "C" have conflicts: \
259 # N: meth: expected "Callable[[], int]", got "int"
260
261 [case testProtocolMethodVsAttributeErrors2]
262 from typing import Protocol
263
264 class P(Protocol):
265 @property
266 def meth(self) -> int:
267 pass
268 class C:
269 def meth(self) -> int:
270 pass
271 x: P = C() # E: Incompatible types in assignment (expression has type "C", variable has type "P") \
272 # N: Following member(s) of "C" have conflicts: \
273 # N: meth: expected "int", got "Callable[[], int]"
274 [builtins fixtures/property.pyi]
275
276 [case testCannotAssignNormalToProtocol]
277 from typing import Protocol
278
279 class P(Protocol):
280 def meth(self) -> int:
281 pass
282 class C:
283 def meth(self) -> int:
284 pass
285
286 x: C
287 y: P
288 x = y # E: Incompatible types in assignment (expression has type "P", variable has type "C")
289
290 [case testIndependentProtocolSubtyping]
291 from typing import Protocol
292
293 class P1(Protocol):
294 def meth(self) -> int:
295 pass
296 class P2(Protocol):
297 def meth(self) -> int:
298 pass
299
300 x1: P1
301 x2: P2
302
303 x1 = x2
304 x2 = x1
305
306 def f1(x: P1) -> None: pass
307 def f2(x: P2) -> None: pass
308
309 f1(x2)
310 f2(x1)
311
312 [case testNoneDisablesProtocolImplementation]
313 from typing import Protocol
314
315 class MyHashable(Protocol):
316 def __my_hash__(self) -> int:
317 return 0
318
319 class C:
320 __my_hash__ = None
321
322 var: MyHashable = C() # E: Incompatible types in assignment (expression has type "C", variable has type "MyHashable") \
323 # N: Following member(s) of "C" have conflicts: \
324 # N: __my_hash__: expected "Callable[[], int]", got "None"
325
326 [case testNoneDisablesProtocolSubclassingWithStrictOptional]
327 from typing import Protocol
328
329 class MyHashable(Protocol):
330 def __my_hash__(self) -> int:
331 return 0
332
333 class C(MyHashable):
334 __my_hash__ = None # E: Incompatible types in assignment \
335 (expression has type "None", base class "MyHashable" defined the type as "Callable[[], int]")
336
337 [case testProtocolsWithNoneAndStrictOptional]
338 from typing import Protocol
339 class P(Protocol):
340 x = 0 # type: int
341
342 class C:
343 x = None
344
345 x: P = C() # Error!
346 def f(x: P) -> None: pass
347 f(C()) # Error!
348 [out]
349 main:8: error: Incompatible types in assignment (expression has type "C", variable has type "P")
350 main:8: note: Following member(s) of "C" have conflicts:
351 main:8: note: x: expected "int", got "None"
352 main:10: error: Argument 1 to "f" has incompatible type "C"; expected "P"
353 main:10: note: Following member(s) of "C" have conflicts:
354 main:10: note: x: expected "int", got "None"
355
356 -- Semanal errors in protocol types
357 -- --------------------------------
358
359 [case testBasicSemanalErrorsInProtocols]
360
361 from typing import Protocol, Generic, TypeVar, Iterable
362
363 T = TypeVar('T', covariant=True)
364 S = TypeVar('S', covariant=True)
365
366 class P1(Protocol[T, T]): # E: Duplicate type variables in Generic[...] or Protocol[...]
367 def meth(self) -> T:
368 pass
369
370 class P2(Protocol[T], Protocol[S]): # E: Only single Generic[...] or Protocol[...] can be in bases
371 def meth(self) -> T:
372 pass
373
374 class P3(Protocol[T], Generic[S]): # E: Only single Generic[...] or Protocol[...] can be in bases
375 def meth(self) -> T:
376 pass
377
378 class P4(Protocol[T]):
379 attr: Iterable[S] # E: Type variable "__main__.S" is unbound \
380 # N: (Hint: Use "Generic[S]" or "Protocol[S]" base class to bind "S" inside a class) \
381 # N: (Hint: Use "S" in function signature to bind "S" inside a function)
382
383 class P5(Iterable[S], Protocol[T]): # E: If Generic[...] or Protocol[...] is present it should list all type variables
384 def meth(self) -> T:
385 pass
386
387 [case testProhibitSelfDefinitionInProtocols]
388 from typing import Protocol
389
390 class P(Protocol):
391 def __init__(self, a: int) -> None:
392 self.a = a # E: Protocol members cannot be defined via assignment to self \
393 # E: "P" has no attribute "a"
394
395 class B: pass
396 class C:
397 def __init__(self, a: int) -> None:
398 pass
399
400 x: P
401 x = B()
402 # The above has an incompatible __init__, but mypy ignores this for nominal subtypes?
403 x = C(1)
404
405 class P2(Protocol):
406 a: int
407 def __init__(self) -> None:
408 self.a = 1
409
410 class B2(P2):
411 a: int
412
413 x2: P2 = B2() # OK
414
415 [case testProtocolAndRuntimeAreDefinedAlsoInTypingExtensions]
416 from typing_extensions import Protocol, runtime_checkable
417
418 @runtime_checkable
419 class P(Protocol):
420 def meth(self) -> int:
421 pass
422
423 x: object
424 if isinstance(x, P):
425 reveal_type(x) # N: Revealed type is "__main__.P"
426 reveal_type(x.meth()) # N: Revealed type is "builtins.int"
427
428 class C:
429 def meth(self) -> int:
430 pass
431
432 z: P = C()
433 [builtins fixtures/dict.pyi]
434
435 [case testProtocolsCannotInheritFromNormal]
436 from typing import Protocol
437
438 class C: pass
439 class D: pass
440
441 class P(C, Protocol): # E: All bases of a protocol must be protocols
442 attr: int
443
444 class P2(P, D, Protocol): # E: All bases of a protocol must be protocols
445 pass
446
447 P2() # E: Cannot instantiate protocol class "P2"
448 p: P2
449 reveal_type(p.attr) # N: Revealed type is "builtins.int"
450
451 -- Generic protocol types
452 -- ----------------------
453
454 [case testGenericMethodWithProtocol]
455 from typing import Protocol, TypeVar
456 T = TypeVar('T')
457
458 class P(Protocol):
459 def meth(self, x: int) -> int:
460 return x
461 class C:
462 def meth(self, x: T) -> T:
463 return x
464
465 x: P = C()
466
467 [case testGenericMethodWithProtocol2]
468 from typing import Protocol, TypeVar
469 T = TypeVar('T')
470
471 class P(Protocol):
472 def meth(self, x: T) -> T:
473 return x
474 class C:
475 def meth(self, x: int) -> int:
476 return x
477
478 x: P = C()
479 [out]
480 main:11: error: Incompatible types in assignment (expression has type "C", variable has type "P")
481 main:11: note: Following member(s) of "C" have conflicts:
482 main:11: note: Expected:
483 main:11: note: def [T] meth(self, x: T) -> T
484 main:11: note: Got:
485 main:11: note: def meth(self, x: int) -> int
486
487 [case testAutomaticProtocolVariance]
488 from typing import TypeVar, Protocol
489
490 T = TypeVar('T')
491
492 # In case of these errors we proceed with declared variance.
493 class Pco(Protocol[T]): # E: Invariant type variable "T" used in protocol where covariant one is expected
494 def meth(self) -> T:
495 pass
496 class Pcontra(Protocol[T]): # E: Invariant type variable "T" used in protocol where contravariant one is expected
497 def meth(self, x: T) -> None:
498 pass
499 class Pinv(Protocol[T]):
500 attr: T
501
502 class A: pass
503 class B(A): pass
504
505 x1: Pco[B]
506 y1: Pco[A]
507 if int():
508 x1 = y1 # E: Incompatible types in assignment (expression has type "Pco[A]", variable has type "Pco[B]")
509 if int():
510 y1 = x1 # E: Incompatible types in assignment (expression has type "Pco[B]", variable has type "Pco[A]")
511
512 x2: Pcontra[B]
513 y2: Pcontra[A]
514 if int():
515 y2 = x2 # E: Incompatible types in assignment (expression has type "Pcontra[B]", variable has type "Pcontra[A]")
516 if int():
517 x2 = y2 # E: Incompatible types in assignment (expression has type "Pcontra[A]", variable has type "Pcontra[B]")
518
519 x3: Pinv[B]
520 y3: Pinv[A]
521 if int():
522 y3 = x3 # E: Incompatible types in assignment (expression has type "Pinv[B]", variable has type "Pinv[A]")
523 if int():
524 x3 = y3 # E: Incompatible types in assignment (expression has type "Pinv[A]", variable has type "Pinv[B]")
525
526 [case testProtocolVarianceWithCallableAndList]
527 from typing import Protocol, TypeVar, Callable, List
528 T = TypeVar('T')
529 S = TypeVar('S')
530 T_co = TypeVar('T_co', covariant=True)
531
532 class P(Protocol[T, S]): # E: Invariant type variable "T" used in protocol where covariant one is expected \
533 # E: Invariant type variable "S" used in protocol where contravariant one is expected
534 def fun(self, callback: Callable[[T], S]) -> None: pass
535
536 class P2(Protocol[T_co]): # E: Covariant type variable "T_co" used in protocol where invariant one is expected
537 lst: List[T_co]
538 [builtins fixtures/list.pyi]
539
540
541 [case testProtocolConstraintsUnsolvableWithSelfAnnotation1]
542 # https://github.com/python/mypy/issues/11020
543 from typing import overload, Protocol, TypeVar
544
545 I = TypeVar('I', covariant=True)
546 V_contra = TypeVar('V_contra', contravariant=True)
547
548 class C(Protocol[I]):
549 def __abs__(self: 'C[V_contra]') -> 'C[V_contra]':
550 ...
551
552 @overload
553 def f(self: 'C', q: int) -> int:
554 ...
555 @overload
556 def f(self: 'C[float]', q: float) -> 'C[float]':
557 ...
558 [builtins fixtures/bool.pyi]
559
560
561 [case testProtocolConstraintsUnsolvableWithSelfAnnotation2]
562 # https://github.com/python/mypy/issues/11020
563 from typing import Protocol, TypeVar
564
565 I = TypeVar('I', covariant=True)
566 V = TypeVar('V')
567
568 class C(Protocol[I]):
569 def g(self: 'C[V]') -> 'C[V]':
570 ...
571
572 class D:
573 pass
574
575 x: C = D() # E: Incompatible types in assignment (expression has type "D", variable has type "C[Any]")
576 [builtins fixtures/bool.pyi]
577
578
579 [case testProtocolConstraintsUnsolvableWithSelfAnnotation3]
580 # https://github.com/python/mypy/issues/11020
581 from typing import Protocol, TypeVar
582
583 I = TypeVar('I', covariant=True)
584 V = TypeVar('V')
585
586 class C(Protocol[I]):
587 def g(self: 'C[V]') -> 'C[V]':
588 ...
589
590 class D:
591 def g(self) -> D:
592 ...
593
594 x: C = D()
595 [builtins fixtures/bool.pyi]
596
597
598 [case testProtocolVarianceWithUnusedVariable]
599 from typing import Protocol, TypeVar
600 T = TypeVar('T')
601
602 class P(Protocol[T]): # E: Invariant type variable "T" used in protocol where covariant one is expected
603 attr: int
604
605 [case testGenericProtocolsInference1]
606 from typing import Protocol, Sequence, TypeVar
607
608 T = TypeVar('T', covariant=True)
609
610 class Closeable(Protocol[T]):
611 def close(self) -> T:
612 pass
613
614 class F:
615 def close(self) -> int:
616 return 0
617
618 def close(arg: Closeable[T]) -> T:
619 return arg.close()
620
621 def close_all(args: Sequence[Closeable[T]]) -> T:
622 for arg in args:
623 arg.close()
624 return args[0].close()
625
626 arg: Closeable[int]
627
628 reveal_type(close(F())) # N: Revealed type is "builtins.int"
629 reveal_type(close(arg)) # N: Revealed type is "builtins.int"
630 reveal_type(close_all([F()])) # N: Revealed type is "builtins.int"
631 reveal_type(close_all([arg])) # N: Revealed type is "builtins.int"
632 [builtins fixtures/isinstancelist.pyi]
633 [typing fixtures/typing-medium.pyi]
634
635 [case testProtocolGenericInference2]
636 from typing import Generic, TypeVar, Protocol
637 T = TypeVar('T')
638 S = TypeVar('S')
639
640 class P(Protocol[T, S]):
641 x: T
642 y: S
643
644 class C:
645 x: int
646 y: int
647
648 def fun3(x: P[T, T]) -> T:
649 pass
650 reveal_type(fun3(C())) # N: Revealed type is "builtins.int"
651
652 [case testProtocolGenericInferenceCovariant]
653 from typing import Generic, TypeVar, Protocol
654 T = TypeVar('T', covariant=True)
655 S = TypeVar('S', covariant=True)
656 U = TypeVar('U')
657
658 class P(Protocol[T, S]):
659 def x(self) -> T: pass
660 def y(self) -> S: pass
661
662 class C:
663 def x(self) -> int: pass
664 def y(self) -> int: pass
665
666 def fun4(x: U, y: P[U, U]) -> U:
667 pass
668 reveal_type(fun4('a', C())) # N: Revealed type is "builtins.object"
669
670 [case testUnrealtedGenericProtocolsEquivalent]
671 from typing import TypeVar, Protocol
672 T = TypeVar('T')
673
674 class PA(Protocol[T]):
675 attr: int
676 def meth(self) -> T: pass
677 def other(self, arg: T) -> None: pass
678 class PB(Protocol[T]): # exactly the same as above
679 attr: int
680 def meth(self) -> T: pass
681 def other(self, arg: T) -> None: pass
682
683 def fun(x: PA[T]) -> PA[T]:
684 y: PB[T] = x
685 z: PB[T]
686 return z
687
688 x: PA
689 y: PB
690 x = y
691 y = x
692
693 xi: PA[int]
694 yi: PB[int]
695 xi = yi
696 yi = xi
697
698 [case testGenericSubProtocols]
699 from typing import TypeVar, Protocol, Tuple, Generic
700
701 T = TypeVar('T')
702 S = TypeVar('S')
703
704 class P1(Protocol[T]):
705 attr1: T
706 class P2(P1[T], Protocol[T, S]):
707 attr2: Tuple[T, S]
708
709 class C:
710 def __init__(self, a1: int, a2: Tuple[int, int]) -> None:
711 self.attr1 = a1
712 self.attr2 = a2
713
714 c: C
715 var: P2[int, int] = c
716 var2: P2[int, str] = c # E: Incompatible types in assignment (expression has type "C", variable has type "P2[int, str]") \
717 # N: Following member(s) of "C" have conflicts: \
718 # N: attr2: expected "tuple[int, str]", got "tuple[int, int]"
719
720 class D(Generic[T]):
721 attr1: T
722 class E(D[T]):
723 attr2: Tuple[T, T]
724
725 def f(x: T) -> T:
726 z: P2[T, T] = E[T]()
727 y: P2[T, T] = D[T]() # E: Incompatible types in assignment (expression has type "D[T]", variable has type "P2[T, T]") \
728 # N: "D" is missing following "P2" protocol member: \
729 # N: attr2
730 return x
731 [builtins fixtures/isinstancelist.pyi]
732
733 [case testGenericSubProtocolsExtensionInvariant]
734 from typing import TypeVar, Protocol, Union
735
736 T = TypeVar('T')
737 S = TypeVar('S')
738
739 class P1(Protocol[T]):
740 attr1: T
741 class P2(Protocol[T]):
742 attr2: T
743 class P(P1[T], P2[S], Protocol):
744 pass
745
746 class C:
747 attr1: int
748 attr2: str
749
750 class A:
751 attr1: A
752 class B:
753 attr2: B
754 class D(A, B): pass
755
756 x: P = D() # Same as P[Any, Any]
757
758 var: P[Union[int, P], Union[P, str]] = C() # E: Incompatible types in assignment (expression has type "C", variable has type "P[int | P[Any, Any], P[Any, Any] | str]") \
759 # N: Following member(s) of "C" have conflicts: \
760 # N: attr1: expected "int | P[Any, Any]", got "int" \
761 # N: attr2: expected "P[Any, Any] | str", got "str"
762
763 [case testGenericSubProtocolsExtensionCovariant]
764 from typing import TypeVar, Protocol, Union
765
766 T = TypeVar('T', covariant=True)
767 S = TypeVar('S', covariant=True)
768
769 class P1(Protocol[T]):
770 def attr1(self) -> T: pass
771 class P2(Protocol[T]):
772 def attr2(self) -> T: pass
773 class P(P1[T], P2[S], Protocol):
774 pass
775
776 class C:
777 def attr1(self) -> int: pass
778 def attr2(self) -> str: pass
779
780 var: P[Union[int, P], Union[P, str]] = C() # OK for covariant
781 var2: P[Union[str, P], Union[P, int]] = C()
782 [out]
783 main:18: error: Incompatible types in assignment (expression has type "C", variable has type "P[str | P[Any, Any], P[Any, Any] | int]")
784 main:18: note: Following member(s) of "C" have conflicts:
785 main:18: note: Expected:
786 main:18: note: def attr1(self) -> str | P[Any, Any]
787 main:18: note: Got:
788 main:18: note: def attr1(self) -> int
789 main:18: note: Expected:
790 main:18: note: def attr2(self) -> P[Any, Any] | int
791 main:18: note: Got:
792 main:18: note: def attr2(self) -> str
793
794 [case testSelfTypesWithProtocolsBehaveAsWithNominal]
795 from typing import Protocol, TypeVar
796
797 T = TypeVar('T', bound='Shape')
798 class Shape(Protocol):
799 def combine(self: T, other: T) -> T:
800 pass
801
802 class NonProtoShape:
803 def combine(self: T, other: T) -> T:
804 pass
805 class Circle:
806 def combine(self: T, other: Shape) -> T:
807 pass
808 class Triangle:
809 def combine(self, other: Shape) -> Shape:
810 pass
811 class Bad:
812 def combine(self, other: int) -> str:
813 pass
814
815 def f(s: Shape) -> None: pass
816 f(NonProtoShape())
817 f(Circle())
818 s: Shape
819 if int():
820 s = Triangle()
821 s = Bad()
822
823 n2: NonProtoShape = s
824 [out]
825 main:26: error: Incompatible types in assignment (expression has type "Triangle", variable has type "Shape")
826 main:26: note: Following member(s) of "Triangle" have conflicts:
827 main:26: note: Expected:
828 main:26: note: def combine(self, other: Triangle) -> Triangle
829 main:26: note: Got:
830 main:26: note: def combine(self, other: Shape) -> Shape
831 main:27: error: Incompatible types in assignment (expression has type "Bad", variable has type "Shape")
832 main:27: note: Following member(s) of "Bad" have conflicts:
833 main:27: note: Expected:
834 main:27: note: def combine(self, other: Bad) -> Bad
835 main:27: note: Got:
836 main:27: note: def combine(self, other: int) -> str
837 main:29: error: Incompatible types in assignment (expression has type "Shape", variable has type "NonProtoShape")
838
839 [case testBadVarianceInProtocols]
840 from typing import Protocol, TypeVar
841
842 T_co = TypeVar('T_co', covariant=True)
843 T_contra = TypeVar('T_contra', contravariant=True)
844
845 class Proto(Protocol[T_co, T_contra]): # type: ignore
846 def one(self, x: T_co) -> None: # E: Cannot use a covariant type variable as a parameter
847 pass
848 def other(self) -> T_contra: # E: Cannot use a contravariant type variable as return type
849 pass
850
851 # Check that we respect user overrides of variance after the errors are reported
852 x: Proto[int, float]
853 y: Proto[float, int]
854 y = x # OK
855 [builtins fixtures/list.pyi]
856
857 [case testSubtleBadVarianceInProtocols]
858 from typing import Protocol, TypeVar, Iterable, Sequence
859
860 T_co = TypeVar('T_co', covariant=True)
861 T_contra = TypeVar('T_contra', contravariant=True)
862
863 class Proto(Protocol[T_co, T_contra]): # E: Covariant type variable "T_co" used in protocol where contravariant one is expected \
864 # E: Contravariant type variable "T_contra" used in protocol where covariant one is expected
865 def one(self, x: Iterable[T_co]) -> None:
866 pass
867 def other(self) -> Sequence[T_contra]:
868 pass
869
870 # Check that we respect user overrides of variance after the errors are reported
871 x: Proto[int, float]
872 y: Proto[float, int]
873 y = x # OK
874 [builtins fixtures/list.pyi]
875
876 -- Recursive protocol types
877 -- ------------------------
878
879 [case testRecursiveProtocols1]
880 from typing import Protocol, Sequence, List, Generic, TypeVar
881
882 T = TypeVar('T')
883
884 class Traversable(Protocol):
885 @property
886 def leaves(self) -> Sequence[Traversable]: pass
887
888 class C: pass
889
890 class D(Generic[T]):
891 leaves: List[D[T]]
892
893 t: Traversable
894 t = D[int]() # OK
895 if int():
896 t = C() # E: Incompatible types in assignment (expression has type "C", variable has type "Traversable")
897 [builtins fixtures/list.pyi]
898 [typing fixtures/typing-medium.pyi]
899
900 [case testRecursiveProtocols2]
901 from typing import Protocol, TypeVar
902
903 T = TypeVar('T')
904 class Linked(Protocol[T]):
905 val: T
906 def next(self) -> Linked[T]: pass
907
908 class L:
909 val: int
910 def next(self) -> L: pass
911
912 def last(seq: Linked[T]) -> T:
913 pass
914
915 reveal_type(last(L())) # N: Revealed type is "builtins.int"
916 [builtins fixtures/list.pyi]
917
918 [case testRecursiveProtocolSubtleMismatch]
919 from typing import Protocol, TypeVar
920
921 T = TypeVar('T')
922 class Linked(Protocol[T]):
923 val: T
924 def next(self) -> Linked[T]: pass
925 class L:
926 val: int
927 def next(self) -> int: pass
928
929 def last(seq: Linked[T]) -> T:
930 pass
931 last(L()) # E: Argument 1 to "last" has incompatible type "L"; expected "Linked[Never]"
932
933 [case testMutuallyRecursiveProtocols]
934 from typing import Protocol, Sequence, List
935
936 class P1(Protocol):
937 @property
938 def attr1(self) -> Sequence[P2]: pass
939 class P2(Protocol):
940 @property
941 def attr2(self) -> Sequence[P1]: pass
942
943 class C: pass
944 class A:
945 attr1: List[B]
946 class B:
947 attr2: List[A]
948
949 t: P1
950 t = A() # OK
951 if int():
952 t = B() # E: Incompatible types in assignment (expression has type "B", variable has type "P1")
953 t = C() # E: Incompatible types in assignment (expression has type "C", variable has type "P1")
954 [builtins fixtures/list.pyi]
955 [typing fixtures/typing-medium.pyi]
956
957 [case testMutuallyRecursiveProtocolsTypesWithSubteMismatch]
958 from typing import Protocol, Sequence, List
959
960 class P1(Protocol):
961 @property
962 def attr1(self) -> Sequence[P2]: pass
963 class P2(Protocol):
964 @property
965 def attr2(self) -> Sequence[P1]: pass
966
967 class C: pass
968 class A:
969 attr1: List[B]
970 class B:
971 attr2: List[C]
972
973 t: P1
974 t = A() # E: Incompatible types in assignment (expression has type "A", variable has type "P1") \
975 # N: Following member(s) of "A" have conflicts: \
976 # N: attr1: expected "Sequence[P2]", got "list[B]"
977 [builtins fixtures/list.pyi]
978
979 [case testMutuallyRecursiveProtocolsTypesWithSubteMismatchWriteable]
980 from typing import Protocol
981
982 class P1(Protocol):
983 @property
984 def attr1(self) -> P2: pass
985 class P2(Protocol):
986 attr2: P1
987
988 class A:
989 attr1: B
990 class B:
991 attr2: A
992
993 x: P1 = A() # E: Incompatible types in assignment (expression has type "A", variable has type "P1") \
994 # N: Following member(s) of "A" have conflicts: \
995 # N: attr1: expected "P2", got "B"
996 [builtins fixtures/property.pyi]
997
998 [case testTwoUncomfortablyIncompatibleProtocolsWithoutRunningInIssue9771]
999 from typing import cast, Protocol, TypeVar, Union
1000
1001 T1 = TypeVar("T1", covariant=True)
1002 T2 = TypeVar("T2")
1003
1004 class P1(Protocol[T1]):
1005 def b(self) -> int: ...
1006 def a(self, other: "P1[T2]") -> T1: ...
1007
1008 class P2(Protocol[T1]):
1009 def a(self, other: Union[P1[T2], "P2[T2]"]) -> T1: ...
1010
1011 p11: P1 = cast(P1, 1)
1012 p12: P1 = cast(P2, 1) # E
1013 p21: P2 = cast(P1, 1)
1014 p22: P2 = cast(P2, 1) # E
1015 [out]
1016 main:14: error: Incompatible types in assignment (expression has type "P2[Any]", variable has type "P1[Any]")
1017 main:14: note: "P2" is missing following "P1" protocol member:
1018 main:14: note: b
1019 main:15: error: Incompatible types in assignment (expression has type "P1[Any]", variable has type "P2[Any]")
1020 main:15: note: Following member(s) of "P1[Any]" have conflicts:
1021 main:15: note: Expected:
1022 main:15: note: def [T2] a(self, other: P1[T2] | P2[T2]) -> Any
1023 main:15: note: Got:
1024 main:15: note: def [T2] a(self, other: P1[T2]) -> Any
1025
1026 [case testHashable]
1027
1028 from typing import Hashable, Iterable
1029
1030 def f(x: Hashable) -> None:
1031 pass
1032
1033 def g(x: Iterable[str]) -> None:
1034 f(x) # E: Argument 1 to "f" has incompatible type "Iterable[str]"; expected "Hashable"
1035
1036 [builtins fixtures/object_hashable.pyi]
1037 [typing fixtures/typing-full.pyi]
1038
1039 -- FIXME: things like this should work
1040 [case testWeirdRecursiveInferenceForProtocols-skip]
1041 from typing import Protocol, TypeVar, Generic
1042 T_co = TypeVar('T_co', covariant=True)
1043 T = TypeVar('T')
1044
1045 class P(Protocol[T_co]):
1046 def meth(self) -> P[T_co]: pass
1047
1048 class C(Generic[T]):
1049 def meth(self) -> C[T]: pass
1050
1051 x: C[int]
1052 def f(arg: P[T]) -> T: pass
1053 reveal_type(f(x)) #E: Revealed type is "builtins.int"
1054
1055 -- @property, @classmethod and @staticmethod in protocol types
1056 -- -----------------------------------------------------------
1057
1058 [case testCannotInstantiateAbstractMethodExplicitProtocolSubtypes]
1059 from typing import Protocol
1060 from abc import abstractmethod
1061
1062 class P(Protocol):
1063 @abstractmethod
1064 def meth(self) -> int:
1065 pass
1066
1067 class A(P):
1068 pass
1069
1070 A() # E: Cannot instantiate abstract class "A" with abstract attribute "meth"
1071
1072 class C(A):
1073 def meth(self) -> int:
1074 pass
1075 class C2(P):
1076 def meth(self) -> int:
1077 pass
1078
1079 C()
1080 C2()
1081
1082 [case testCannotInstantiateAbstractVariableExplicitProtocolSubtypes]
1083 from typing import Protocol
1084
1085 class P(Protocol):
1086 attr: int
1087
1088 class A(P):
1089 pass
1090
1091 A() # E: Cannot instantiate abstract class "A" with abstract attribute "attr"
1092
1093 class C(A):
1094 attr: int
1095 class C2(P):
1096 def __init__(self) -> None:
1097 self.attr = 1
1098
1099 C()
1100 C2()
1101
1102 class P2(Protocol):
1103 attr: int = 1
1104
1105 class B(P2): pass
1106 B() # OK, attr is not abstract
1107
1108 [case testClassVarsInProtocols]
1109 from typing import Protocol, ClassVar
1110
1111 class PInst(Protocol):
1112 v: int
1113
1114 class PClass(Protocol):
1115 v: ClassVar[int]
1116
1117 class CInst:
1118 v: int
1119
1120 class CClass:
1121 v: ClassVar[int]
1122
1123 x: PInst
1124 y: PClass
1125
1126 x = CInst()
1127 if int():
1128 x = CClass() # E: Incompatible types in assignment (expression has type "CClass", variable has type "PInst") \
1129 # N: Protocol member PInst.v expected instance variable, got class variable
1130 y = CClass()
1131 if int():
1132 y = CInst() # E: Incompatible types in assignment (expression has type "CInst", variable has type "PClass") \
1133 # N: Protocol member PClass.v expected class variable, got instance variable
1134
1135 [case testPropertyInProtocols]
1136 from typing import Protocol
1137
1138 class PP(Protocol):
1139 @property
1140 def attr(self) -> int:
1141 pass
1142
1143 class P(Protocol):
1144 attr: int
1145
1146 x: P
1147 y: PP
1148 y = x
1149
1150 x2: P
1151 y2: PP
1152 x2 = y2 # E: Incompatible types in assignment (expression has type "PP", variable has type "P") \
1153 # N: Protocol member P.attr expected settable variable, got read-only attribute
1154 [builtins fixtures/property.pyi]
1155
1156 [case testClassVarProtocolImmutable]
1157 from typing import Protocol, ClassVar
1158
1159 class P(Protocol):
1160 @property
1161 def x(self) -> int: ...
1162
1163 class C:
1164 x: ClassVar[int]
1165
1166 class Bad:
1167 x: ClassVar[str]
1168
1169 x: P = C()
1170 y: P = Bad() # E: Incompatible types in assignment (expression has type "Bad", variable has type "P") \
1171 # N: Following member(s) of "Bad" have conflicts: \
1172 # N: x: expected "int", got "str"
1173 [builtins fixtures/property.pyi]
1174
1175 [case testSettablePropertyInProtocols]
1176 from typing import Protocol
1177
1178 class PPS(Protocol):
1179 @property
1180 def attr(self) -> int:
1181 pass
1182 @attr.setter
1183 def attr(self, x: int) -> None:
1184 pass
1185
1186 class PP(Protocol):
1187 @property
1188 def attr(self) -> int:
1189 pass
1190
1191 class P(Protocol):
1192 attr: int
1193
1194 x: P
1195 z: PPS
1196 z = x
1197
1198 x2: P
1199 z2: PPS
1200 x2 = z2
1201
1202 y3: PP
1203 z3: PPS
1204 y3 = z3
1205
1206 y4: PP
1207 z4: PPS
1208 z4 = y4 # E: Incompatible types in assignment (expression has type "PP", variable has type "PPS") \
1209 # N: Protocol member PPS.attr expected settable variable, got read-only attribute
1210 [builtins fixtures/property.pyi]
1211
1212 [case testFinalAttributeProtocol]
1213 from typing import Protocol, Final
1214
1215 class P(Protocol):
1216 x: int
1217
1218 class C:
1219 def __init__(self, x: int) -> None:
1220 self.x = x
1221 class CF:
1222 def __init__(self, x: int) -> None:
1223 self.x: Final = x
1224
1225 x: P
1226 y: P
1227 x = C(42)
1228 y = CF(42) # E: Incompatible types in assignment (expression has type "CF", variable has type "P") \
1229 # N: Protocol member P.x expected settable variable, got read-only attribute
1230
1231 [case testStaticAndClassMethodsInProtocols]
1232 from typing import Protocol, Type, TypeVar
1233
1234 class P(Protocol):
1235 def meth(self, x: int) -> str:
1236 pass
1237
1238 class PC(Protocol):
1239 @classmethod
1240 def meth(cls, x: int) -> str:
1241 pass
1242
1243 class B:
1244 @staticmethod
1245 def meth(x: int) -> str:
1246 pass
1247
1248 class C:
1249 def meth(self, x: int) -> str:
1250 pass
1251
1252 x: P
1253 x = C()
1254 if int():
1255 x = B()
1256
1257 y: PC
1258 y = B()
1259 if int():
1260 y = C() \
1261 # E: Incompatible types in assignment (expression has type "C", variable has type "PC") \
1262 # N: Protocol member PC.meth expected class or static method
1263 [builtins fixtures/classmethod.pyi]
1264
1265 [case testOverloadedMethodsInProtocols]
1266 from typing import overload, Protocol, Union, Optional
1267
1268 class P(Protocol):
1269 @overload
1270 def f(self, x: int) -> Optional[int]: pass
1271 @overload
1272 def f(self, x: str) -> Optional[str]: pass
1273
1274 class C:
1275 def f(self, x: Union[int, str]) -> None:
1276 pass
1277 class D:
1278 def f(self, x: int) -> None:
1279 pass
1280
1281 x: P = C()
1282 if int():
1283 x = D()
1284 [out]
1285 main:18: error: Incompatible types in assignment (expression has type "D", variable has type "P")
1286 main:18: note: Following member(s) of "D" have conflicts:
1287 main:18: note: Expected:
1288 main:18: note: @overload
1289 main:18: note: def f(self, x: int) -> int | None
1290 main:18: note: @overload
1291 main:18: note: def f(self, x: str) -> str | None
1292 main:18: note: Got:
1293 main:18: note: def f(self, x: int) -> None
1294
1295 [case testCannotInstantiateProtocolWithOverloadedUnimplementedMethod]
1296 from typing import overload, Protocol
1297
1298 class P(Protocol):
1299 @overload
1300 def meth(self, x: int) -> int: pass
1301 @overload
1302 def meth(self, x: str) -> bytes: pass
1303 class C(P):
1304 pass
1305 C() # E: Cannot instantiate abstract class "C" with abstract attribute "meth"
1306
1307 [case testCanUseOverloadedImplementationsInProtocols]
1308 from typing import overload, Protocol, Union
1309 class P(Protocol):
1310 @overload
1311 def meth(self, x: int) -> int: pass
1312 @overload
1313 def meth(self, x: str) -> bool: pass
1314 def meth(self, x: Union[int, str]):
1315 if isinstance(x, int):
1316 return x
1317 return True
1318
1319 class C(P):
1320 pass
1321 x = C()
1322 reveal_type(x.meth('hi')) # N: Revealed type is "builtins.bool"
1323 [builtins fixtures/isinstance.pyi]
1324
1325 [case testProtocolsWithIdenticalOverloads]
1326 from typing import overload, Protocol
1327
1328 class PA(Protocol):
1329 @overload
1330 def meth(self, x: int) -> int: pass
1331 @overload
1332 def meth(self, x: str) -> bytes: pass
1333 class PB(Protocol): # identical to above
1334 @overload
1335 def meth(self, x: int) -> int: pass
1336 @overload
1337 def meth(self, x: str) -> bytes: pass
1338
1339 x: PA
1340 y: PB
1341 x = y
1342 def fun(arg: PB) -> None: pass
1343 fun(x)
1344
1345 [case testProtocolsWithIncompatibleOverloads]
1346 from typing import overload, Protocol
1347
1348 class PA(Protocol):
1349 @overload
1350 def meth(self, x: int) -> int: pass
1351 @overload
1352 def meth(self, x: str) -> bytes: pass
1353 class PB(Protocol):
1354 @overload
1355 def meth(self, x: int) -> int: pass
1356 @overload
1357 def meth(self, x: bytes) -> str: pass
1358
1359 x: PA
1360 y: PB
1361 x = y
1362 [out]
1363 main:16: error: Incompatible types in assignment (expression has type "PB", variable has type "PA")
1364 main:16: note: Following member(s) of "PB" have conflicts:
1365 main:16: note: Expected:
1366 main:16: note: @overload
1367 main:16: note: def meth(self, x: int) -> int
1368 main:16: note: @overload
1369 main:16: note: def meth(self, x: str) -> bytes
1370 main:16: note: Got:
1371 main:16: note: @overload
1372 main:16: note: def meth(self, x: int) -> int
1373 main:16: note: @overload
1374 main:16: note: def meth(self, x: bytes) -> str
1375
1376 [case testProtocolWithMultiContravariantTypeVarOverloads]
1377 from typing import overload, Protocol, TypeVar
1378
1379 T1 = TypeVar("T1", contravariant=True)
1380 T2 = TypeVar("T2", contravariant=True)
1381
1382 class A(Protocol[T1, T2]):
1383 @overload
1384 def method(self, a: T1) -> None: ...
1385 @overload
1386 def method(self, a: T2) -> None: ...
1387
1388
1389 -- Join and meet with protocol types
1390 -- ---------------------------------
1391
1392 [case testJoinProtocolWithProtocol]
1393 from typing import Protocol
1394
1395 class P(Protocol):
1396 attr: int
1397 class P2(Protocol):
1398 attr: int
1399 attr2: str
1400
1401 x: P
1402 y: P2
1403
1404 l0 = [x, x]
1405 l1 = [y, y]
1406 l = [x, y]
1407 reveal_type(l0) # N: Revealed type is "builtins.list[__main__.P]"
1408 reveal_type(l1) # N: Revealed type is "builtins.list[__main__.P2]"
1409 reveal_type(l) # N: Revealed type is "builtins.list[__main__.P]"
1410 [builtins fixtures/list.pyi]
1411
1412 [case testJoinOfIncompatibleProtocols]
1413 from typing import Protocol
1414
1415 class P(Protocol):
1416 attr: int
1417 class P2(Protocol):
1418 attr2: str
1419
1420 x: P
1421 y: P2
1422 reveal_type([x, y]) # N: Revealed type is "builtins.list[builtins.object]"
1423 [builtins fixtures/list.pyi]
1424
1425 [case testJoinProtocolWithNormal]
1426 from typing import Protocol
1427
1428 class P(Protocol):
1429 attr: int
1430
1431 class C:
1432 attr: int
1433
1434 x: P
1435 y: C
1436
1437 l = [x, y]
1438
1439 reveal_type(l) # N: Revealed type is "builtins.list[__main__.P]"
1440 [builtins fixtures/list.pyi]
1441
1442 [case testMeetProtocolWithProtocol]
1443 from typing import Protocol, Callable, TypeVar
1444
1445 class P(Protocol):
1446 attr: int
1447 class P2(Protocol):
1448 attr: int
1449 attr2: str
1450
1451 T = TypeVar('T')
1452 def f(x: Callable[[T, T], None]) -> T: pass
1453 def g(x: P, y: P2) -> None: pass
1454 reveal_type(f(g)) # N: Revealed type is "__main__.P2"
1455
1456 [case testMeetOfIncompatibleProtocols]
1457 # flags: --no-strict-optional
1458 from typing import Protocol, Callable, TypeVar
1459
1460 class P(Protocol):
1461 attr: int
1462 class P2(Protocol):
1463 attr2: str
1464
1465 T = TypeVar('T')
1466 def f(x: Callable[[T, T], None]) -> T: pass
1467 def g(x: P, y: P2) -> None: pass
1468 x = f(g)
1469 reveal_type(x) # N: Revealed type is "None"
1470
1471 [case testMeetProtocolWithNormal]
1472 from typing import Protocol, Callable, TypeVar
1473
1474 class P(Protocol):
1475 attr: int
1476 class C:
1477 attr: int
1478
1479 T = TypeVar('T')
1480 def f(x: Callable[[T, T], None]) -> T: pass
1481 def g(x: P, y: C) -> None: pass
1482 reveal_type(f(g)) # N: Revealed type is "__main__.C"
1483
1484 [case testInferProtocolFromProtocol]
1485 from typing import Protocol, Sequence, TypeVar, Generic
1486
1487 T = TypeVar('T')
1488 class Box(Protocol[T]):
1489 content: T
1490 class Linked(Protocol[T]):
1491 val: T
1492 def next(self) -> Linked[T]: pass
1493
1494 class L(Generic[T]):
1495 val: Box[T]
1496 def next(self) -> L[T]: pass
1497
1498 def last(seq: Linked[T]) -> T:
1499 pass
1500
1501 reveal_type(last(L[int]())) # N: Revealed type is "__main__.Box[builtins.int]"
1502 reveal_type(last(L[str]()).content) # N: Revealed type is "builtins.str"
1503
1504 [case testOverloadOnProtocol]
1505 from typing import overload, Protocol, runtime_checkable
1506
1507 @runtime_checkable
1508 class P1(Protocol):
1509 attr1: int
1510 class P2(Protocol):
1511 attr2: str
1512
1513 class C1:
1514 attr1: int
1515 class C2:
1516 attr2: str
1517 class C: pass
1518
1519 @overload
1520 def f(x: P1) -> int: ...
1521 @overload
1522 def f(x: P2) -> str: ...
1523 def f(x: object) -> object:
1524 if isinstance(x, P1):
1525 return P1.attr1
1526 if isinstance(x, P2): # E: Only @runtime_checkable protocols can be used with instance and class checks
1527 return P2.attr2
1528 return None
1529
1530 reveal_type(f(C1())) # N: Revealed type is "builtins.int"
1531 reveal_type(f(C2())) # N: Revealed type is "builtins.str"
1532 class D(C1, C2): pass # Compatible with both P1 and P2
1533 # TODO: Should this return a union instead?
1534 reveal_type(f(D())) # N: Revealed type is "builtins.int"
1535 f(C()) # E: No overload variant of "f" matches argument type "C" \
1536 # N: Possible overload variants: \
1537 # N: def f(x: P1) -> int \
1538 # N: def f(x: P2) -> str
1539 [builtins fixtures/isinstance.pyi]
1540 [typing fixtures/typing-full.pyi]
1541
1542 -- Unions of protocol types
1543 -- ------------------------
1544
1545 [case testBasicUnionsOfProtocols]
1546 from typing import Union, Protocol
1547
1548 class P1(Protocol):
1549 attr1: int
1550 class P2(Protocol):
1551 attr2: int
1552
1553 class C1:
1554 attr1: int
1555 class C2:
1556 attr2: int
1557 class C(C1, C2):
1558 pass
1559
1560 class B: ...
1561
1562 x: Union[P1, P2]
1563
1564 x = C1()
1565 if int():
1566 x = C2()
1567 x = C()
1568 x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "P1 | P2")
1569
1570 [case testUnionsOfNormalClassesWithProtocols]
1571 from typing import Protocol, Union
1572
1573 class P1(Protocol):
1574 attr1: int
1575 class P2(Protocol):
1576 attr2: int
1577
1578 class C1:
1579 attr1: int
1580 class C2:
1581 attr2: int
1582 class C(C1, C2):
1583 pass
1584
1585 class D1:
1586 attr1: int
1587
1588 def f1(x: P1) -> None:
1589 pass
1590 def f2(x: P2) -> None:
1591 pass
1592
1593 x: Union[C1, C2]
1594 y: Union[C1, D1]
1595 z: Union[C, D1]
1596
1597 f1(x) # E: Argument 1 to "f1" has incompatible type "C1 | C2"; expected "P1"
1598 f1(y)
1599 f1(z)
1600 f2(x) # E: Argument 1 to "f2" has incompatible type "C1 | C2"; expected "P2"
1601 f2(z) # E: Argument 1 to "f2" has incompatible type "C | D1"; expected "P2"
1602
1603 -- Type[] with protocol types
1604 -- --------------------------
1605
1606 [case testInstantiationProtocolInTypeForFunctions]
1607 from typing import Type, Protocol
1608
1609 class P(Protocol):
1610 def m(self) -> None: return None
1611 class P1(Protocol):
1612 def m(self) -> None: pass
1613 class Pbad(Protocol):
1614 def mbad(self) -> int: pass
1615 class B(P): pass
1616 class C:
1617 def m(self) -> None:
1618 pass
1619
1620 def f(cls: Type[P]) -> P:
1621 return cls() # OK
1622 def g() -> P:
1623 return P() # E: Cannot instantiate protocol class "P"
1624
1625 f(P) # E: Only concrete class can be given where "type[P]" is expected
1626 f(B) # OK
1627 f(C) # OK
1628 x: Type[P1]
1629 xbad: Type[Pbad]
1630 f(x) # OK
1631 f(xbad) # E: Argument 1 to "f" has incompatible type "type[Pbad]"; expected "type[P]"
1632
1633 [case testInstantiationProtocolInTypeForAliases]
1634 from typing import Type, Protocol
1635
1636 class P(Protocol):
1637 def m(self) -> None: pass
1638 class C:
1639 def m(self) -> None:
1640 pass
1641
1642 def f(cls: Type[P]) -> P:
1643 return cls() # OK
1644
1645 Alias = P
1646 GoodAlias = C
1647 Alias() # E: Cannot instantiate protocol class "P"
1648 GoodAlias()
1649 f(Alias) # E: Only concrete class can be given where "type[P]" is expected
1650 f(GoodAlias)
1651
1652 [case testInstantiationProtocolInTypeForVariables]
1653 # flags: --no-strict-optional
1654 from typing import Type, Protocol
1655
1656 class P(Protocol):
1657 def m(self) -> None: return None
1658 class B(P): pass
1659 class C:
1660 def m(self) -> None:
1661 pass
1662
1663 var: Type[P]
1664 var()
1665 if int():
1666 var = P # E: Can only assign concrete classes to a variable of type "type[P]"
1667 var = B # OK
1668 var = C # OK
1669
1670 var_old = None # type: Type[P] # Old syntax for variable annotations
1671 var_old()
1672 if int():
1673 var_old = P # E: Can only assign concrete classes to a variable of type "type[P]"
1674 var_old = B # OK
1675 var_old = C # OK
1676
1677 [case testInstantiationProtocolInTypeForClassMethods]
1678 from typing import Type, Protocol
1679
1680 class Logger:
1681 @staticmethod
1682 def log(a: Type[C]):
1683 pass
1684 class C(Protocol):
1685 @classmethod
1686 def action(cls) -> None:
1687 cls() #OK for classmethods
1688 Logger.log(cls) #OK for classmethods
1689 [builtins fixtures/classmethod.pyi]
1690
1691 -- isinstance() with @runtime_checkable protocols
1692 -- ----------------------------------------------
1693
1694 [case testSimpleRuntimeProtocolCheck]
1695 from typing import Protocol, runtime_checkable
1696
1697 @runtime_checkable
1698 class C: # E: @runtime_checkable can only be used with protocol classes
1699 pass
1700
1701 class P(Protocol):
1702 def meth(self) -> None:
1703 pass
1704
1705 @runtime_checkable
1706 class R(Protocol):
1707 def meth(self) -> int:
1708 pass
1709
1710 x: object
1711
1712 if isinstance(x, P): # E: Only @runtime_checkable protocols can be used with instance and class checks
1713 reveal_type(x) # N: Revealed type is "__main__.P"
1714
1715 if isinstance(x, R):
1716 reveal_type(x) # N: Revealed type is "__main__.R"
1717 reveal_type(x.meth()) # N: Revealed type is "builtins.int"
1718 [builtins fixtures/isinstance.pyi]
1719 [typing fixtures/typing-full.pyi]
1720
1721 [case testRuntimeIterableProtocolCheck]
1722 from typing import Iterable, List, Union
1723
1724 x: Union[int, List[str]]
1725
1726 if isinstance(x, Iterable):
1727 reveal_type(x) # N: Revealed type is "builtins.list[builtins.str]"
1728 [builtins fixtures/isinstancelist.pyi]
1729 [typing fixtures/typing-full.pyi]
1730
1731 [case testConcreteClassesInProtocolsIsInstance]
1732 # flags: --warn-unreachable
1733 from typing import Protocol, runtime_checkable, TypeVar, Generic
1734
1735 T = TypeVar('T')
1736
1737 @runtime_checkable
1738 class P1(Protocol):
1739 def meth1(self) -> int:
1740 pass
1741 @runtime_checkable
1742 class P2(Protocol):
1743 def meth2(self) -> int:
1744 pass
1745 @runtime_checkable
1746 class P(P1, P2, Protocol):
1747 pass
1748
1749 class C1(Generic[T]):
1750 def meth1(self) -> T:
1751 pass
1752 class C2:
1753 def meth2(self) -> int:
1754 pass
1755 class C(C1[int], C2): pass
1756
1757 c = C()
1758 if isinstance(c, P1):
1759 reveal_type(c) # N: Revealed type is "__main__.C"
1760 else:
1761 reveal_type(c) # E: Statement is unreachable
1762 if isinstance(c, P):
1763 reveal_type(c) # N: Revealed type is "__main__.C"
1764 else:
1765 reveal_type(c) # E: Statement is unreachable
1766
1767 c1i: C1[int]
1768 if isinstance(c1i, P1):
1769 reveal_type(c1i) # N: Revealed type is "__main__.C1[builtins.int]"
1770 else:
1771 reveal_type(c1i) # E: Statement is unreachable
1772 if isinstance(c1i, P):
1773 reveal_type(c1i) # N: Revealed type is "__main__.<subclass of "__main__.C1[builtins.int]" and "__main__.P">"
1774 else:
1775 reveal_type(c1i) # N: Revealed type is "__main__.C1[builtins.int]"
1776
1777 c1s: C1[str]
1778 if isinstance(c1s, P1): # E: Subclass of "C1[str]" and "P1" cannot exist: would have incompatible method signatures
1779 reveal_type(c1s) # E: Statement is unreachable
1780 else:
1781 reveal_type(c1s) # N: Revealed type is "__main__.C1[builtins.str]"
1782
1783 c2: C2
1784 if isinstance(c2, P):
1785 reveal_type(c2) # N: Revealed type is "__main__.<subclass of "__main__.C2" and "__main__.P">"
1786 else:
1787 reveal_type(c2) # N: Revealed type is "__main__.C2"
1788
1789 [builtins fixtures/isinstancelist.pyi]
1790 [typing fixtures/typing-full.pyi]
1791
1792 [case testConcreteClassesUnionInProtocolsIsInstance]
1793 from typing import Protocol, runtime_checkable, TypeVar, Generic, Union
1794
1795 T = TypeVar('T')
1796
1797 @runtime_checkable
1798 class P1(Protocol):
1799 def meth1(self) -> int:
1800 pass
1801 @runtime_checkable
1802 class P2(Protocol):
1803 def meth2(self) -> int:
1804 pass
1805
1806 class C1(Generic[T]):
1807 def meth1(self) -> T:
1808 pass
1809 class C2:
1810 def meth2(self) -> int:
1811 pass
1812
1813 x: Union[C1[int], C2]
1814 if isinstance(x, P1):
1815 reveal_type(x) # N: Revealed type is "__main__.C1[builtins.int]"
1816 else:
1817 reveal_type(x) # N: Revealed type is "__main__.C2"
1818
1819 if isinstance(x, P2):
1820 reveal_type(x) # N: Revealed type is "__main__.C2"
1821 else:
1822 reveal_type(x) # N: Revealed type is "__main__.C1[builtins.int]"
1823 [builtins fixtures/isinstancelist.pyi]
1824 [typing fixtures/typing-full.pyi]
1825
1826 -- Non-Instances and protocol types (Callable vs __call__ etc.)
1827 -- ------------------------------------------------------------
1828
1829 [case testBasicTupleStructuralSubtyping]
1830 from typing import Tuple, TypeVar, Protocol
1831
1832 T = TypeVar('T', covariant=True)
1833
1834 class MyProto(Protocol[T]):
1835 def __len__(self) -> T:
1836 pass
1837
1838 t: Tuple[int, str]
1839 def f(x: MyProto[int]) -> None:
1840 pass
1841 f(t) # OK
1842
1843 y: MyProto[str]
1844 y = t # E: Incompatible types in assignment (expression has type "tuple[int, str]", variable has type "MyProto[str]")
1845 [builtins fixtures/isinstancelist.pyi]
1846
1847 [case testBasicNamedTupleStructuralSubtyping]
1848 from typing import NamedTuple, TypeVar, Protocol
1849
1850 T = TypeVar('T', covariant=True)
1851 S = TypeVar('S', covariant=True)
1852
1853 class P(Protocol[T, S]):
1854 @property
1855 def x(self) -> T: pass
1856 @property
1857 def y(self) -> S: pass
1858
1859 class N(NamedTuple):
1860 x: int
1861 y: str
1862 class N2(NamedTuple):
1863 x: int
1864 class N3(NamedTuple):
1865 x: int
1866 y: int
1867
1868 z: N
1869 z3: N3
1870
1871 def fun(x: P[int, str]) -> None:
1872 pass
1873 def fun2(x: P[int, int]) -> None:
1874 pass
1875 def fun3(x: P[T, T]) -> T:
1876 return x.x
1877
1878 fun(z)
1879 fun2(z) # E: Argument 1 to "fun2" has incompatible type "N"; expected "P[int, int]" \
1880 # N: Following member(s) of "N" have conflicts: \
1881 # N: y: expected "int", got "str"
1882
1883 fun(N2(1)) # E: Argument 1 to "fun" has incompatible type "N2"; expected "P[int, str]" \
1884 # N: "N2" is missing following "P" protocol member: \
1885 # N: y
1886
1887 reveal_type(fun3(z)) # N: Revealed type is "builtins.object"
1888
1889 reveal_type(fun3(z3)) # N: Revealed type is "builtins.int"
1890 [builtins fixtures/list.pyi]
1891
1892 [case testBasicCallableStructuralSubtyping]
1893 from typing import Callable, Generic, TypeVar
1894
1895 def apply(f: Callable[[int], int], x: int) -> int:
1896 return f(x)
1897
1898 class Add5:
1899 def __call__(self, x: int) -> int:
1900 return x + 5
1901
1902 apply(Add5(), 5)
1903
1904 T = TypeVar('T')
1905 def apply_gen(f: Callable[[T], T]) -> T:
1906 pass
1907
1908 reveal_type(apply_gen(Add5())) # N: Revealed type is "builtins.int"
1909 def apply_str(f: Callable[[str], int], x: str) -> int:
1910 return f(x)
1911 apply_str(Add5(), 'a') # E: Argument 1 to "apply_str" has incompatible type "Add5"; expected "Callable[[str], int]" \
1912 # N: "Add5.__call__" has type "def __call__(self, x: int) -> int"
1913 [builtins fixtures/isinstancelist.pyi]
1914
1915 [case testMoreComplexCallableStructuralSubtyping]
1916 from mypy_extensions import Arg, VarArg
1917 from typing import Protocol, Callable
1918
1919 def call_soon(cb: Callable[[Arg(int, 'x'), VarArg(str)], int]): pass
1920
1921 class Good:
1922 def __call__(self, x: int, *rest: str) -> int: pass
1923 class Bad1:
1924 def __call__(self, x: int, *rest: int) -> int: pass
1925 class Bad2:
1926 def __call__(self, y: int, *rest: str) -> int: pass
1927 call_soon(Good())
1928 call_soon(Bad1()) # E: Argument 1 to "call_soon" has incompatible type "Bad1"; expected "def (x: int, *str) -> int" \
1929 # N: "Bad1.__call__" has type "def __call__(self, x: int, *rest: int) -> int"
1930 call_soon(Bad2()) # E: Argument 1 to "call_soon" has incompatible type "Bad2"; expected "def (x: int, *str) -> int" \
1931 # N: "Bad2.__call__" has type "def __call__(self, y: int, *rest: str) -> int"
1932 [builtins fixtures/isinstancelist.pyi]
1933
1934 [case testStructuralSupportForPartial]
1935 from typing import Callable, TypeVar, Generic, Any
1936
1937 T = TypeVar('T')
1938
1939 class partial(Generic[T]):
1940 def __init__(self, func: Callable[..., T], *args: Any) -> None: ...
1941 def __call__(self, *args: Any) -> T: ...
1942
1943 def inc(a: int, temp: str) -> int:
1944 pass
1945
1946 def foo(f: Callable[[int], T]) -> T:
1947 return f(1)
1948
1949 reveal_type(foo(partial(inc, 'temp'))) # N: Revealed type is "builtins.int"
1950 [builtins fixtures/list.pyi]
1951
1952 [case testStructuralInferenceForCallable]
1953 from typing import Callable, TypeVar, Tuple
1954
1955 T = TypeVar('T')
1956 S = TypeVar('S')
1957
1958 class Actual:
1959 def __call__(self, arg: int) -> str: pass
1960
1961 def fun(cb: Callable[[T], S]) -> Tuple[T, S]: pass
1962 reveal_type(fun(Actual())) # N: Revealed type is "tuple[builtins.int, builtins.str]"
1963 [builtins fixtures/tuple.pyi]
1964
1965 -- Standard protocol types (SupportsInt, Sized, etc.)
1966 -- --------------------------------------------------
1967
1968 -- More tests could be added for types from typing converted to protocols
1969
1970 [case testBasicSizedProtocol]
1971 from typing import Sized
1972
1973 class Foo:
1974 def __len__(self) -> int:
1975 return 42
1976
1977 def bar(a: Sized) -> int:
1978 return a.__len__()
1979
1980 bar(Foo())
1981 bar((1, 2))
1982 bar(1) # E: Argument 1 to "bar" has incompatible type "int"; expected "Sized"
1983
1984 [builtins fixtures/isinstancelist.pyi]
1985 [typing fixtures/typing-medium.pyi]
1986
1987 [case testBasicSupportsIntProtocol]
1988 from typing import SupportsInt
1989
1990 class Bar:
1991 def __int__(self):
1992 return 1
1993
1994 def foo(a: SupportsInt):
1995 pass
1996
1997 foo(Bar())
1998 foo('no way') # E: Argument 1 to "foo" has incompatible type "str"; expected "SupportsInt"
1999
2000 [builtins fixtures/isinstancelist.pyi]
2001 [typing fixtures/typing-medium.pyi]
2002
2003 -- Additional tests and corner cases for protocols
2004 -- ----------------------------------------------
2005
2006 [case testAnyWithProtocols]
2007 from typing import Protocol, Any, TypeVar
2008
2009 T = TypeVar('T')
2010
2011 class P1(Protocol):
2012 attr1: int
2013 class P2(Protocol[T]):
2014 attr2: T
2015 class P3(Protocol):
2016 attr: P3
2017
2018 def f1(x: P1) -> None: pass
2019 def f2(x: P2[str]) -> None: pass
2020 def f3(x: P3) -> None: pass
2021
2022 class C1:
2023 attr1: Any
2024 class C2:
2025 attr2: Any
2026 class C3:
2027 attr: Any
2028
2029 f1(C1())
2030 f2(C2())
2031 f3(C3())
2032
2033 f2(C3()) # E: Argument 1 to "f2" has incompatible type "C3"; expected "P2[str]"
2034 a: Any
2035 f1(a)
2036 f2(a)
2037 f3(a)
2038
2039 [case testErrorsForProtocolsInDifferentPlaces]
2040 from typing import Protocol
2041
2042 class P(Protocol):
2043 attr1: int
2044 attr2: str
2045 attr3: int
2046
2047 class C:
2048 attr1: str
2049 @property
2050 def attr2(self) -> int: pass
2051
2052 x: P = C() # E: Incompatible types in assignment (expression has type "C", variable has type "P") \
2053 # N: "C" is missing following "P" protocol member: \
2054 # N: attr3 \
2055 # N: Following member(s) of "C" have conflicts: \
2056 # N: attr1: expected "int", got "str" \
2057 # N: attr2: expected "str", got "int" \
2058 # N: Protocol member P.attr2 expected settable variable, got read-only attribute
2059
2060 def f(x: P) -> P:
2061 return C() # E: Incompatible return value type (got "C", expected "P") \
2062 # N: "C" is missing following "P" protocol member: \
2063 # N: attr3 \
2064 # N: Following member(s) of "C" have conflicts: \
2065 # N: attr1: expected "int", got "str" \
2066 # N: attr2: expected "str", got "int" \
2067 # N: Protocol member P.attr2 expected settable variable, got read-only attribute
2068
2069 f(C()) # E: Argument 1 to "f" has incompatible type "C"; expected "P" \
2070 # N: "C" is missing following "P" protocol member: \
2071 # N: attr3 \
2072 # N: Following member(s) of "C" have conflicts: \
2073 # N: attr1: expected "int", got "str" \
2074 # N: attr2: expected "str", got "int" \
2075 # N: Protocol member P.attr2 expected settable variable, got read-only attribute
2076 [builtins fixtures/list.pyi]
2077
2078 [case testIterableProtocolOnClass]
2079 from typing import TypeVar, Iterator
2080 T = TypeVar('T', bound='A')
2081
2082 class A:
2083 def __iter__(self: T) -> Iterator[T]: pass
2084
2085 class B(A): pass
2086
2087 reveal_type(list(b for b in B())) # N: Revealed type is "builtins.list[__main__.B]"
2088 reveal_type(list(B())) # N: Revealed type is "builtins.list[__main__.B]"
2089 [builtins fixtures/list.pyi]
2090
2091 [case testIterableProtocolOnMetaclass]
2092 from typing import TypeVar, Iterator, Type
2093 T = TypeVar('T')
2094
2095 class EMeta(type):
2096 def __iter__(self: Type[T]) -> Iterator[T]: pass
2097
2098 class E(metaclass=EMeta):
2099 pass
2100
2101 class C(E):
2102 pass
2103
2104 reveal_type(list(c for c in C)) # N: Revealed type is "builtins.list[__main__.C]"
2105 reveal_type(list(C)) # N: Revealed type is "builtins.list[__main__.C]"
2106 [builtins fixtures/list.pyi]
2107
2108 [case testClassesGetattrWithProtocols]
2109 from typing import Protocol
2110
2111 class P(Protocol):
2112 attr: int
2113
2114 class PP(Protocol):
2115 @property
2116 def attr(self) -> int:
2117 pass
2118
2119 class C:
2120 def __getattr__(self, attr: str) -> int:
2121 pass
2122 class C2(C):
2123 def __setattr__(self, attr: str, val: int) -> None:
2124 pass
2125
2126 class D:
2127 def __getattr__(self, attr: str) -> str:
2128 pass
2129
2130 def fun(x: P) -> None:
2131 reveal_type(P.attr) # N: Revealed type is "builtins.int"
2132 def fun_p(x: PP) -> None:
2133 reveal_type(P.attr) # N: Revealed type is "builtins.int"
2134
2135 fun(C()) # E: Argument 1 to "fun" has incompatible type "C"; expected "P" \
2136 # N: Protocol member P.attr expected settable variable, got read-only attribute
2137 fun(C2())
2138 fun_p(D()) # E: Argument 1 to "fun_p" has incompatible type "D"; expected "PP" \
2139 # N: Following member(s) of "D" have conflicts: \
2140 # N: attr: expected "int", got "str"
2141 fun_p(C()) # OK
2142 [builtins fixtures/list.pyi]
2143
2144 [case testImplicitTypesInProtocols]
2145 from typing import Protocol
2146
2147 class P(Protocol):
2148 x = 1 # E: All protocol members must have explicitly declared types
2149
2150 class C:
2151 x: int
2152
2153 class D:
2154 x: str
2155
2156 x: P
2157 x = D() # E: Incompatible types in assignment (expression has type "D", variable has type "P") \
2158 # N: Following member(s) of "D" have conflicts: \
2159 # N: x: expected "int", got "str"
2160 x = C() # OK
2161 [builtins fixtures/list.pyi]
2162
2163 [case testProtocolIncompatibilityWithGenericMethod]
2164 from typing import Protocol, TypeVar
2165
2166 T = TypeVar('T')
2167 S = TypeVar('S')
2168
2169 class A(Protocol):
2170 def f(self, x: T) -> None: pass
2171 class B:
2172 def f(self, x: S, y: T) -> None: pass
2173
2174 x: A = B()
2175 [out]
2176 main:11: error: Incompatible types in assignment (expression has type "B", variable has type "A")
2177 main:11: note: Following member(s) of "B" have conflicts:
2178 main:11: note: Expected:
2179 main:11: note: def [T] f(self, x: T) -> None
2180 main:11: note: Got:
2181 main:11: note: def [S, T] f(self, x: S, y: T) -> None
2182
2183 [case testProtocolIncompatibilityWithGenericMethodBounded]
2184 from typing import Protocol, TypeVar
2185
2186 T = TypeVar('T')
2187 S = TypeVar('S', bound=int)
2188
2189 class A(Protocol):
2190 def f(self, x: T) -> None: pass
2191 class B:
2192 def f(self, x: S, y: T) -> None: pass
2193
2194 x: A = B()
2195 [out]
2196 main:11: error: Incompatible types in assignment (expression has type "B", variable has type "A")
2197 main:11: note: Following member(s) of "B" have conflicts:
2198 main:11: note: Expected:
2199 main:11: note: def [T] f(self, x: T) -> None
2200 main:11: note: Got:
2201 main:11: note: def [S: int, T] f(self, x: S, y: T) -> None
2202
2203 [case testProtocolIncompatibilityWithGenericRestricted]
2204 from typing import Protocol, TypeVar
2205
2206 T = TypeVar('T')
2207 S = TypeVar('S', int, str)
2208
2209 class A(Protocol):
2210 def f(self, x: T) -> None: pass
2211 class B:
2212 def f(self, x: S, y: T) -> None: pass
2213
2214 x: A = B()
2215 [out]
2216 main:11: error: Incompatible types in assignment (expression has type "B", variable has type "A")
2217 main:11: note: Following member(s) of "B" have conflicts:
2218 main:11: note: Expected:
2219 main:11: note: def [T] f(self, x: T) -> None
2220 main:11: note: Got:
2221 main:11: note: def [S: (int, str), T] f(self, x: S, y: T) -> None
2222
2223 [case testProtocolIncompatibilityWithManyOverloads]
2224 from typing import Protocol, overload
2225
2226 class C1: pass
2227 class C2: pass
2228 class A(Protocol):
2229 @overload
2230 def f(self, x: int) -> int: pass
2231 @overload
2232 def f(self, x: str) -> str: pass
2233 @overload
2234 def f(self, x: C1) -> C2: pass
2235 @overload
2236 def f(self, x: C2) -> C1: pass
2237
2238 class B:
2239 def f(self) -> None: pass
2240
2241 x: A = B()
2242 [out]
2243 main:18: error: Incompatible types in assignment (expression has type "B", variable has type "A")
2244 main:18: note: Following member(s) of "B" have conflicts:
2245 main:18: note: Expected:
2246 main:18: note: @overload
2247 main:18: note: def f(self, x: int) -> int
2248 main:18: note: @overload
2249 main:18: note: def f(self, x: str) -> str
2250 main:18: note: @overload
2251 main:18: note: def f(self, x: C1) -> C2
2252 main:18: note: @overload
2253 main:18: note: def f(self, x: C2) -> C1
2254 main:18: note: Got:
2255 main:18: note: def f(self) -> None
2256
2257 [case testProtocolIncompatibilityWithManyConflicts]
2258 from typing import Protocol
2259
2260 class A(Protocol):
2261 def f(self, x: int) -> None: pass
2262 def g(self, x: int) -> None: pass
2263 def h(self, x: int) -> None: pass
2264 def i(self, x: int) -> None: pass
2265 class B:
2266 def f(self, x: str) -> None: pass
2267 def g(self, x: str) -> None: pass
2268 def h(self, x: str) -> None: pass
2269 def i(self, x: str) -> None: pass
2270
2271 x: A = B()
2272 [out]
2273 main:14: error: Incompatible types in assignment (expression has type "B", variable has type "A")
2274 main:14: note: Following member(s) of "B" have conflicts:
2275 main:14: note: Expected:
2276 main:14: note: def f(self, x: int) -> None
2277 main:14: note: Got:
2278 main:14: note: def f(self, x: str) -> None
2279 main:14: note: Expected:
2280 main:14: note: def g(self, x: int) -> None
2281 main:14: note: Got:
2282 main:14: note: def g(self, x: str) -> None
2283 main:14: note: <2 more conflict(s) not shown>
2284
2285 [case testProtocolIncompatibilityWithUnionType]
2286 from typing import Any, Optional, Protocol
2287
2288 class A(Protocol):
2289 def execute(self, statement: Any, *args: Any, **kwargs: Any) -> None: ...
2290
2291 class B(Protocol):
2292 def execute(self, stmt: Any, *args: Any, **kwargs: Any) -> None: ...
2293 def cool(self) -> None: ...
2294
2295 def func1(arg: A) -> None: ...
2296 def func2(arg: Optional[A]) -> None: ...
2297
2298 x: B
2299 func1(x)
2300 func2(x)
2301 [builtins fixtures/dict.pyi]
2302 [out]
2303 main:14: error: Argument 1 to "func1" has incompatible type "B"; expected "A"
2304 main:14: note: Following member(s) of "B" have conflicts:
2305 main:14: note: Expected:
2306 main:14: note: def execute(self, statement: Any, *args: Any, **kwargs: Any) -> None
2307 main:14: note: Got:
2308 main:14: note: def execute(self, stmt: Any, *args: Any, **kwargs: Any) -> None
2309 main:15: error: Argument 1 to "func2" has incompatible type "B"; expected "A | None"
2310 main:15: note: Following member(s) of "B" have conflicts:
2311 main:15: note: Expected:
2312 main:15: note: def execute(self, statement: Any, *args: Any, **kwargs: Any) -> None
2313 main:15: note: Got:
2314 main:15: note: def execute(self, stmt: Any, *args: Any, **kwargs: Any) -> None
2315
2316 [case testDontShowNotesForTupleAndIterableProtocol]
2317 from typing import Iterable, Sequence, Protocol, NamedTuple
2318
2319 class N(NamedTuple):
2320 x: int
2321
2322 def f1(x: Iterable[str]) -> None: pass
2323 def f2(x: Sequence[str]) -> None: pass
2324
2325 # The errors below should be short
2326 f1(N(1)) # E: Argument 1 to "f1" has incompatible type "N"; expected "Iterable[str]"
2327 f2(N(2)) # E: Argument 1 to "f2" has incompatible type "N"; expected "Sequence[str]"
2328 [builtins fixtures/tuple.pyi]
2329
2330 [case testNotManyFlagConflitsShownInProtocols]
2331 from typing import Protocol
2332
2333 class AllSettable(Protocol):
2334 a: int
2335 b: int
2336 c: int
2337 d: int
2338
2339 class AllReadOnly:
2340 @property
2341 def a(self) -> int: pass
2342 @property
2343 def b(self) -> int: pass
2344 @property
2345 def c(self) -> int: pass
2346 @property
2347 def d(self) -> int: pass
2348
2349 x: AllSettable = AllReadOnly()
2350 [builtins fixtures/property.pyi]
2351 [out]
2352 main:19: error: Incompatible types in assignment (expression has type "AllReadOnly", variable has type "AllSettable")
2353 main:19: note: Protocol member AllSettable.a expected settable variable, got read-only attribute
2354 main:19: note: Protocol member AllSettable.b expected settable variable, got read-only attribute
2355 main:19: note: <2 more conflict(s) not shown>
2356
2357 [case testProtocolsMoreConflictsNotShown]
2358 from typing import Generic, Protocol, TypeVar
2359
2360 T = TypeVar('T')
2361
2362 class MockMapping(Protocol[T]):
2363 def a(self, x: T) -> int: pass
2364 def b(self, x: T) -> int: pass
2365 def c(self, x: T) -> int: pass
2366 d: T
2367 e: T
2368 f: T
2369
2370 class MockDict(MockMapping[T]):
2371 more: int
2372
2373 def f(x: MockMapping[int]) -> None: pass
2374 x: MockDict[str]
2375 f(x) # E: Argument 1 to "f" has incompatible type "MockDict[str]"; expected "MockMapping[int]"
2376 [builtins fixtures/tuple.pyi]
2377
2378 [case testProtocolNotesForComplexSignatures]
2379 from typing import Protocol, Optional
2380
2381 class P(Protocol):
2382 def meth(self, x: int, *args: str) -> None: pass
2383 def other(self, *args, hint: Optional[str] = None, **kwargs: str) -> None: pass
2384 class C:
2385 def meth(self) -> int: pass
2386 def other(self) -> int: pass
2387
2388 x: P = C()
2389 [builtins fixtures/dict.pyi]
2390 [out]
2391 main:10: error: Incompatible types in assignment (expression has type "C", variable has type "P")
2392 main:10: note: Following member(s) of "C" have conflicts:
2393 main:10: note: Expected:
2394 main:10: note: def meth(self, x: int, *args: str) -> None
2395 main:10: note: Got:
2396 main:10: note: def meth(self) -> int
2397 main:10: note: Expected:
2398 main:10: note: def other(self, *args: Any, hint: str | None = ..., **kwargs: str) -> None
2399 main:10: note: Got:
2400 main:10: note: def other(self) -> int
2401
2402 [case testObjectAllowedInProtocolBases]
2403 from typing import Protocol
2404 class P(Protocol, object):
2405 pass
2406 [out]
2407
2408 [case testNoneSubtypeOfEmptyProtocol]
2409 from typing import Protocol
2410 class P(Protocol):
2411 pass
2412
2413 x: P = None
2414 [out]
2415
2416 [case testNoneSubtypeOfAllProtocolsWithoutStrictOptional]
2417 # flags: --no-strict-optional
2418 from typing import Protocol
2419 class P(Protocol):
2420 attr: int
2421 def meth(self, arg: str) -> str:
2422 pass
2423
2424 x: P = None
2425 [out]
2426
2427 [case testNoneSubtypeOfEmptyProtocolStrict]
2428 from typing import Protocol
2429 class P(Protocol):
2430 pass
2431 x: P = None
2432
2433 class PBad(Protocol):
2434 x: int
2435 y: PBad = None # E: Incompatible types in assignment (expression has type "None", variable has type "PBad")
2436 [out]
2437
2438 [case testOnlyMethodProtocolUsableWithIsSubclass]
2439 from typing import Protocol, runtime_checkable, Union, Type, Sequence, overload
2440 @runtime_checkable
2441 class P(Protocol):
2442 def meth(self) -> int:
2443 pass
2444 @runtime_checkable
2445 class PBad(Protocol):
2446 x: str
2447
2448 class C:
2449 x: str
2450 def meth(self) -> int:
2451 pass
2452 class E: pass
2453
2454 cls: Type[Union[C, E]]
2455 issubclass(cls, PBad) # E: Only protocols that don't have non-method members can be used with issubclass() \
2456 # N: Protocol "PBad" has non-method member(s): x
2457 if issubclass(cls, P):
2458 reveal_type(cls) # N: Revealed type is "type[__main__.C]"
2459 else:
2460 reveal_type(cls) # N: Revealed type is "type[__main__.E]"
2461
2462 @runtime_checkable
2463 class POverload(Protocol):
2464 @overload
2465 def meth(self, a: int) -> float: ...
2466 @overload
2467 def meth(self, a: str) -> Sequence[float]: ...
2468 def meth(self, a):
2469 pass
2470
2471 reveal_type(issubclass(int, POverload)) # N: Revealed type is "builtins.bool"
2472 [builtins fixtures/isinstance.pyi]
2473 [typing fixtures/typing-full.pyi]
2474 [out]
2475
2476 [case testCallableImplementsProtocol]
2477 from typing import Protocol
2478
2479 class Caller(Protocol):
2480 def __call__(self, x: str, *args: int) -> None: ...
2481
2482 def call(x: str, *args: int) -> None:
2483 pass
2484 def bad(x: int, *args: str) -> None:
2485 pass
2486
2487 def func(caller: Caller) -> None:
2488 pass
2489
2490 func(call)
2491 func(bad) # E: Argument 1 to "func" has incompatible type "def bad(x: int, *args: str) -> None"; expected "Caller" \
2492 # N: "Caller.__call__" has type "def __call__(self, x: str, *args: int) -> None"
2493 [builtins fixtures/tuple.pyi]
2494 [out]
2495
2496 [case testCallableImplementsProtocolGeneric]
2497 from typing import Protocol, TypeVar, Tuple
2498
2499 T = TypeVar('T')
2500 S = TypeVar('S')
2501
2502 class Caller(Protocol[T, S]):
2503 def __call__(self, x: T, y: S) -> Tuple[T, S]: ...
2504
2505 def call(x: int, y: str) -> Tuple[int, str]: ...
2506
2507 def func(caller: Caller[T, S]) -> Tuple[T, S]:
2508 pass
2509
2510 reveal_type(func(call)) # N: Revealed type is "tuple[builtins.int, builtins.str]"
2511 [builtins fixtures/tuple.pyi]
2512 [out]
2513
2514 [case testCallableImplementsProtocolGenericTight]
2515 from typing import Protocol, TypeVar
2516
2517 T = TypeVar('T')
2518
2519 class Caller(Protocol):
2520 def __call__(self, x: T) -> T: ...
2521
2522 def call(x: T) -> T: ...
2523 def bad(x: int) -> int: ...
2524
2525 def func(caller: Caller) -> None:
2526 pass
2527
2528 func(call)
2529 func(bad) # E: Argument 1 to "func" has incompatible type "Callable[[int], int]"; expected "Caller" \
2530 # N: "Caller.__call__" has type "def [T] __call__(self, x: T) -> T"
2531 [builtins fixtures/tuple.pyi]
2532 [out]
2533
2534 [case testCallableImplementsProtocolGenericNotGeneric]
2535 from typing import Protocol, TypeVar, Tuple
2536
2537 T = TypeVar('T')
2538
2539 class Caller(Protocol):
2540 def __call__(self, x: int) -> int: ...
2541
2542 def call(x: T) -> T: ...
2543
2544 def bad(x: T) -> Tuple[T, T]: ...
2545
2546 def func(caller: Caller) -> None:
2547 pass
2548
2549 func(call)
2550 func(bad) # E: Argument 1 to "func" has incompatible type "Callable[[T], tuple[T, T]]"; expected "Caller" \
2551 # N: "Caller.__call__" has type "def __call__(self, x: int) -> int"
2552 [builtins fixtures/tuple.pyi]
2553 [out]
2554
2555 [case testCallableImplementsProtocolOverload]
2556 from typing import Protocol, overload, Union
2557
2558 class Caller(Protocol):
2559 @overload
2560 def __call__(self, x: int) -> int: ...
2561 @overload
2562 def __call__(self, x: str) -> str: ...
2563
2564 @overload
2565 def call(x: int) -> int: ...
2566 @overload
2567 def call(x: str) -> str: ...
2568 def call(x: Union[int, str]) -> Union[int, str]:
2569 pass
2570
2571 def bad(x: Union[int, str]) -> Union[int, str]:
2572 pass
2573
2574 def func(caller: Caller) -> None:
2575 pass
2576
2577 func(call)
2578 func(bad) # E: Argument 1 to "func" has incompatible type "Callable[[int | str], int | str]"; expected "Caller" \
2579 # N: "Caller.__call__" has type overloaded function
2580 [out]
2581
2582 [case testCallableImplementsProtocolExtraNote]
2583 from typing import Protocol
2584
2585 class Caller(Protocol):
2586 def __call__(self, x: str, *args: int) -> None: ...
2587
2588 def bad(x: int, *args: str) -> None:
2589 pass
2590
2591 cb: Caller = bad # E: Incompatible types in assignment (expression has type "def bad(x: int, *args: str) -> None", variable has type "Caller") \
2592 # N: "Caller.__call__" has type "def __call__(self, x: str, *args: int) -> None"
2593 [builtins fixtures/tuple.pyi]
2594 [out]
2595
2596 [case testCallableImplementsProtocolArgName]
2597 from typing import Protocol
2598
2599 class Caller(Protocol):
2600 def __call__(self, x: str) -> None: ...
2601
2602 class CallerAnon(Protocol):
2603 def __call__(self, __x: str) -> None: ...
2604
2605 def call(x: str) -> None:
2606 pass
2607 def bad(y: str) -> None:
2608 pass
2609
2610 def func(caller: Caller) -> None:
2611 pass
2612
2613 def anon(caller: CallerAnon) -> None:
2614 pass
2615
2616
2617 func(call)
2618 func(bad) # E: Argument 1 to "func" has incompatible type "Callable[[str], None]"; expected "Caller" \
2619 # N: "Caller.__call__" has type "def __call__(self, x: str) -> None"
2620 anon(bad)
2621 [out]
2622
2623 [case testCallableProtocolVsProtocol]
2624 from typing import Protocol
2625
2626 class One(Protocol):
2627 def __call__(self, x: str) -> None: ...
2628
2629 class Other(Protocol):
2630 def __call__(self, x: str) -> None: ...
2631
2632 class Bad(Protocol):
2633 def __call__(self, zzz: str) -> None: ...
2634
2635 def func(caller: One) -> None:
2636 pass
2637
2638 a: Other
2639 b: Bad
2640
2641 func(a)
2642 func(b) # E: Argument 1 to "func" has incompatible type "Bad"; expected "One" \
2643 # N: "One.__call__" has type "def __call__(self, x: str) -> None"
2644 [out]
2645
2646 [case testJoinProtocolCallback]
2647 from typing import Protocol, Callable
2648
2649 class A: ...
2650 class B(A): ...
2651 class C(B): ...
2652 class D(B): ...
2653
2654 class Call(Protocol):
2655 def __call__(self, x: B) -> C: ...
2656 Normal = Callable[[A], D]
2657
2658 a: Call
2659 b: Normal
2660
2661 reveal_type([a, b]) # N: Revealed type is "builtins.list[def (__main__.B) -> __main__.B]"
2662 reveal_type([b, a]) # N: Revealed type is "builtins.list[def (__main__.B) -> __main__.B]"
2663 [builtins fixtures/list.pyi]
2664 [out]
2665
2666 [case testMeetProtocolCallback]
2667 from typing import Protocol, Callable
2668
2669 class A: ...
2670 class B(A): ...
2671 class C(B): ...
2672 class D(B): ...
2673
2674 class Call(Protocol):
2675 def __call__(self, __x: C) -> B: ...
2676 Normal = Callable[[D], A]
2677
2678 def a(x: Call) -> None: ...
2679 def b(x: Normal) -> None: ...
2680
2681 reveal_type([a, b]) # N: Revealed type is "builtins.list[def (x: def (__main__.B) -> __main__.B)]"
2682 reveal_type([b, a]) # N: Revealed type is "builtins.list[def (x: def (__main__.B) -> __main__.B)]"
2683 [builtins fixtures/list.pyi]
2684 [out]
2685
2686 [case testCallbackProtocolFunctionAttributesSubtyping]
2687 from typing import Protocol
2688
2689 class A(Protocol):
2690 __name__: str
2691 def __call__(self) -> str: ...
2692
2693 class B1(Protocol):
2694 __name__: int
2695 def __call__(self) -> str: ...
2696
2697 class B2(Protocol):
2698 __name__: str
2699 def __call__(self) -> int: ...
2700
2701 class B3(Protocol):
2702 __name__: str
2703 extra_stuff: int
2704 def __call__(self) -> str: ...
2705
2706 def f() -> str: ...
2707
2708 reveal_type(f.__name__) # N: Revealed type is "builtins.str"
2709 a: A = f # OK
2710 b1: B1 = f # E: Incompatible types in assignment (expression has type "Callable[[], str]", variable has type "B1") \
2711 # N: Following member(s) of "function" have conflicts: \
2712 # N: __name__: expected "int", got "str"
2713 b2: B2 = f # E: Incompatible types in assignment (expression has type "Callable[[], str]", variable has type "B2") \
2714 # N: "B2.__call__" has type "Callable[[], int]"
2715 b3: B3 = f # E: Incompatible types in assignment (expression has type "Callable[[], str]", variable has type "B3") \
2716 # N: "function" is missing following "B3" protocol member: \
2717 # N: extra_stuff
2718
2719 [case testCallbackProtocolFunctionAttributesInference]
2720 from typing import Protocol, TypeVar, Generic, Tuple
2721
2722 T = TypeVar("T")
2723 S = TypeVar("S", covariant=True)
2724 class A(Protocol[T, S]):
2725 __name__: T
2726 def __call__(self) -> S: ...
2727
2728 def f() -> int: ...
2729 def test(func: A[T, S]) -> Tuple[T, S]: ...
2730 reveal_type(test(f)) # N: Revealed type is "tuple[builtins.str, builtins.int]"
2731 [builtins fixtures/tuple.pyi]
2732
2733 [case testProtocolsAlwaysABCs]
2734 from typing import Protocol
2735
2736 class P(Protocol): ...
2737 class C(P): ...
2738
2739 reveal_type(C.register(int)) # N: Revealed type is "def () -> builtins.int"
2740 [builtins fixtures/tuple.pyi]
2741 [typing fixtures/typing-full.pyi]
2742 [out]
2743
2744 [case testProtocolVarianceAfterDecorators]
2745 # The test case is simplified, in reality this caused problems with @abstractmethod
2746 # in stubs and test fixtures.
2747 from typing import Protocol, TypeVar
2748
2749 T = TypeVar('T')
2750 def dec(x: T) -> T: ...
2751 alias = dec
2752
2753 class P(Protocol[T]):
2754 @alias
2755 def meth(self, arg: T) -> T: ...
2756 [out]
2757
2758 [case testNamedTupleWithNoArgsCallableField]
2759 from typing import Callable, NamedTuple, Protocol
2760
2761 class N(NamedTuple):
2762 func: Callable[[], str]
2763
2764 class P(Protocol):
2765 @property
2766 def func(self) -> Callable[[], str]: ...
2767
2768 p: P = N(lambda: 'foo')
2769 [builtins fixtures/property.pyi]
2770
2771 [case testNamedTupleWithManyArgsCallableField]
2772 from typing import Callable, NamedTuple, Protocol
2773
2774 class N(NamedTuple):
2775 func: Callable[[str, str, str], str]
2776
2777 class P(Protocol):
2778 @property
2779 def func(self) -> Callable[[str, str, str], str]: ...
2780
2781 p: P = N(lambda a, b, c: 'foo')
2782 [builtins fixtures/property.pyi]
2783
2784 [case testLiteralsAgainstProtocols]
2785 from typing import Final, Literal, SupportsInt, SupportsAbs, TypeVar
2786
2787 T = TypeVar('T')
2788 def abs(x: SupportsAbs[T]) -> T: ...
2789 def foo(x: SupportsInt) -> None: ...
2790
2791 ONE: Final = 1
2792 TWO: Literal[2]
2793 ALL: Literal[1, 2, 3]
2794
2795 foo(ONE)
2796 foo(TWO)
2797 foo(3)
2798
2799 reveal_type(abs(ONE)) # N: Revealed type is "builtins.int"
2800 reveal_type(abs(TWO)) # N: Revealed type is "builtins.int"
2801 reveal_type(abs(3)) # N: Revealed type is "builtins.int"
2802 reveal_type(abs(ALL)) # N: Revealed type is "builtins.int"
2803 [builtins fixtures/float.pyi]
2804 [typing fixtures/typing-full.pyi]
2805
2806 [case testProtocolWithSlots]
2807 from typing import Protocol
2808
2809 class A(Protocol):
2810 __slots__ = ()
2811
2812 [builtins fixtures/tuple.pyi]
2813
2814 [case testProtocolSlotsIsNotProtocolMember]
2815 # https://github.com/python/mypy/issues/11884
2816 from typing import Protocol
2817
2818 class Foo(Protocol):
2819 __slots__ = ()
2820 class NoSlots:
2821 pass
2822 class EmptySlots:
2823 __slots__ = ()
2824 class TupleSlots:
2825 __slots__ = ('x', 'y')
2826 class StringSlots:
2827 __slots__ = 'x y'
2828 class InitSlots:
2829 __slots__ = ('x',)
2830 def __init__(self) -> None:
2831 self.x = None
2832 def foo(f: Foo):
2833 pass
2834
2835 # All should pass:
2836 foo(NoSlots())
2837 foo(EmptySlots())
2838 foo(TupleSlots())
2839 foo(StringSlots())
2840 foo(InitSlots())
2841 [builtins fixtures/tuple.pyi]
2842
2843 [case testProtocolSlotsAndRuntimeCheckable]
2844 from typing import Protocol, runtime_checkable
2845
2846 @runtime_checkable
2847 class Foo(Protocol):
2848 __slots__ = ()
2849 class Bar:
2850 pass
2851 issubclass(Bar, Foo) # Used to be an error, when `__slots__` counted as a protocol member
2852 [builtins fixtures/isinstance.pyi]
2853 [typing fixtures/typing-full.pyi]
2854
2855
2856 [case testProtocolWithClassGetItem]
2857 # https://github.com/python/mypy/issues/11886
2858 from typing import Any, Iterable, Protocol, Union
2859
2860 class B:
2861 ...
2862
2863 class C:
2864 def __class_getitem__(cls, __item: Any) -> Any:
2865 ...
2866
2867 class SupportsClassGetItem(Protocol):
2868 __slots__: Union[str, Iterable[str]] = ()
2869 def __class_getitem__(cls, __item: Any) -> Any:
2870 ...
2871
2872 b1: SupportsClassGetItem = B()
2873 c1: SupportsClassGetItem = C()
2874 [builtins fixtures/tuple.pyi]
2875 [typing fixtures/typing-full.pyi]
2876
2877
2878 [case testNoneVsProtocol]
2879 # mypy: strict-optional
2880 from typing import Protocol
2881
2882 class MyHashable(Protocol):
2883 def __hash__(self) -> int: ...
2884
2885 def f(h: MyHashable) -> None: pass
2886 f(None)
2887
2888 class Proto(Protocol):
2889 def __hash__(self) -> int: ...
2890 def method(self) -> None: ...
2891
2892 def g(h: Proto) -> None: pass
2893 g(None) # E: Argument 1 to "g" has incompatible type "None"; expected "Proto"
2894
2895 class Proto2(Protocol):
2896 def hash(self) -> None: ...
2897
2898 def h(h: Proto2) -> None: pass
2899 h(None) # E: Argument 1 to "h" has incompatible type "None"; expected "Proto2"
2900
2901 class EmptyProto(Protocol): ...
2902
2903 def hh(h: EmptyProto) -> None: pass
2904 hh(None)
2905
2906 # See https://github.com/python/mypy/issues/13081
2907 class SupportsStr(Protocol):
2908 def __str__(self) -> str: ...
2909
2910 def ss(s: SupportsStr) -> None: pass
2911 ss(None)
2912
2913 class HashableStr(Protocol):
2914 def __str__(self) -> str: ...
2915 def __hash__(self) -> int: ...
2916
2917 def hs(n: HashableStr) -> None: pass
2918 hs(None)
2919 [builtins fixtures/tuple.pyi]
2920
2921
2922 [case testPartialTypeProtocol]
2923 # flags: --no-local-partial-types
2924 from typing import Protocol
2925
2926 class Flapper(Protocol):
2927 def flap(self) -> int: ...
2928
2929 class Blooper:
2930 flap = None
2931
2932 def bloop(self, x: Flapper) -> None:
2933 reveal_type([self, x]) # N: Revealed type is "builtins.list[builtins.object]"
2934
2935 class Gleemer:
2936 flap = [] # E: Need type annotation for "flap" (hint: "flap: list[<type>] = ...")
2937
2938 def gleem(self, x: Flapper) -> None:
2939 reveal_type([self, x]) # N: Revealed type is "builtins.list[builtins.object]"
2940 [builtins fixtures/tuple.pyi]
2941
2942
2943 [case testPartialTypeProtocolHashable]
2944 # flags: --no-strict-optional --no-local-partial-types
2945 from typing import Protocol
2946
2947 class Hashable(Protocol):
2948 def __hash__(self) -> int: ...
2949
2950 class ObjectHashable:
2951 def __hash__(self) -> int: ...
2952
2953 class DataArray(ObjectHashable):
2954 __hash__ = None
2955
2956 def f(self, x: Hashable) -> None:
2957 reveal_type([self, x]) # N: Revealed type is "builtins.list[builtins.object]"
2958 [builtins fixtures/tuple.pyi]
2959
2960
2961 [case testPartialTypeProtocolHashableLocalPartialTypes]
2962 # flags: --no-strict-optional --local-partial-types
2963 from typing import Protocol
2964
2965 class Hashable(Protocol):
2966 def __hash__(self) -> int: ...
2967
2968 class ObjectHashable:
2969 def __hash__(self) -> int: ...
2970
2971 class DataArray(ObjectHashable):
2972 __hash__ = None
2973
2974 def f(self, x: Hashable) -> None:
2975 reveal_type([self, x]) # N: Revealed type is "builtins.list[builtins.object]"
2976 [builtins fixtures/tuple.pyi]
2977
2978
2979 [case testPartialAttributeNoneType]
2980 # flags: --no-strict-optional --no-local-partial-types
2981 from typing import Optional, Protocol, runtime_checkable
2982
2983 @runtime_checkable
2984 class MyProtocol(Protocol):
2985 def is_valid(self) -> bool: ...
2986 text: Optional[str]
2987
2988 class MyClass:
2989 text = None
2990 def is_valid(self) -> bool:
2991 reveal_type(self.text) # N: Revealed type is "None"
2992 assert isinstance(self, MyProtocol)
2993 [builtins fixtures/isinstance.pyi]
2994 [typing fixtures/typing-full.pyi]
2995
2996
2997 [case testPartialAttributeNoneTypeStrictOptional]
2998 # flags: --no-local-partial-types
2999 from typing import Optional, Protocol, runtime_checkable
3000
3001 @runtime_checkable
3002 class MyProtocol(Protocol):
3003 def is_valid(self) -> bool: ...
3004 text: Optional[str]
3005
3006 class MyClass:
3007 text = None
3008 def is_valid(self) -> bool:
3009 reveal_type(self.text) # N: Revealed type is "None"
3010 assert isinstance(self, MyProtocol)
3011 [builtins fixtures/isinstance.pyi]
3012 [typing fixtures/typing-full.pyi]
3013
3014 [case testProtocolAndTypeVariableSpecialCase]
3015 from typing import TypeVar, Iterable, Optional, Callable, Protocol
3016
3017 T_co = TypeVar('T_co', covariant=True)
3018
3019 class SupportsNext(Protocol[T_co]):
3020 def __next__(self) -> T_co: ...
3021
3022 N = TypeVar("N", bound=SupportsNext, covariant=True)
3023
3024 class SupportsIter(Protocol[T_co]):
3025 def __iter__(self) -> T_co: ...
3026
3027 def f(i: SupportsIter[N]) -> N: ...
3028
3029 I = TypeVar('I', bound=Iterable)
3030
3031 def g(x: I, y: Iterable) -> None:
3032 f(x)
3033 f(y)
3034
3035 [case testMatchProtocolAgainstOverloadWithAmbiguity]
3036 from typing import TypeVar, Protocol, Union, Generic, overload
3037
3038 T = TypeVar("T", covariant=True)
3039
3040 class slice: pass
3041
3042 class GetItem(Protocol[T]):
3043 def __getitem__(self, k: int) -> T: ...
3044
3045 class Str: # Resembles 'str'
3046 def __getitem__(self, k: Union[int, slice]) -> Str: ...
3047
3048 class Lst(Generic[T]): # Resembles 'list'
3049 def __init__(self, x: T): ...
3050 @overload
3051 def __getitem__(self, k: int) -> T: ...
3052 @overload
3053 def __getitem__(self, k: slice) -> Lst[T]: ...
3054 def __getitem__(self, k): pass
3055
3056 def f(x: GetItem[GetItem[Str]]) -> None: ...
3057
3058 a: Lst[Str]
3059 f(Lst(a))
3060
3061 class Lst2(Generic[T]):
3062 def __init__(self, x: T): ...
3063 # The overload items are tweaked but still compatible
3064 @overload
3065 def __getitem__(self, k: Str) -> None: ...
3066 @overload
3067 def __getitem__(self, k: slice) -> Lst2[T]: ...
3068 @overload
3069 def __getitem__(self, k: Union[int, str]) -> T: ...
3070 def __getitem__(self, k): pass
3071
3072 b: Lst2[Str]
3073 f(Lst2(b))
3074
3075 class Lst3(Generic[T]): # Resembles 'list'
3076 def __init__(self, x: T): ...
3077 # The overload items are no longer compatible (too narrow argument type)
3078 @overload
3079 def __getitem__(self, k: slice) -> Lst3[T]: ...
3080 @overload
3081 def __getitem__(self, k: bool) -> T: ...
3082 def __getitem__(self, k): pass
3083
3084 c: Lst3[Str]
3085 f(Lst3(c)) # E: Argument 1 to "f" has incompatible type "Lst3[Lst3[Str]]"; expected "GetItem[GetItem[Str]]" \
3086 # N: Following member(s) of "Lst3[Lst3[Str]]" have conflicts: \
3087 # N: Expected: \
3088 # N: def __getitem__(self, int, /) -> GetItem[Str] \
3089 # N: Got: \
3090 # N: @overload \
3091 # N: def __getitem__(self, slice, /) -> Lst3[Lst3[Str]] \
3092 # N: @overload \
3093 # N: def __getitem__(self, bool, /) -> Lst3[Str]
3094
3095 [builtins fixtures/list.pyi]
3096 [typing fixtures/typing-full.pyi]
3097
3098 [case testMatchProtocolAgainstOverloadWithMultipleMatchingItems]
3099 from typing import Protocol, overload, TypeVar, Any
3100
3101 _T_co = TypeVar("_T_co", covariant=True)
3102 _T = TypeVar("_T")
3103
3104 class SupportsRound(Protocol[_T_co]):
3105 @overload
3106 def __round__(self) -> int: ...
3107 @overload
3108 def __round__(self, __ndigits: int) -> _T_co: ...
3109
3110 class C:
3111 # This matches both overload items of SupportsRound
3112 def __round__(self, __ndigits: int = ...) -> int: ...
3113
3114 def round(number: SupportsRound[_T], ndigits: int) -> _T: ...
3115
3116 round(C(), 1)
3117
3118 [case testEmptyBodyImplicitlyAbstractProtocol]
3119 from typing import Protocol, overload, Union
3120
3121 class P1(Protocol):
3122 def meth(self) -> int: ...
3123 class B1(P1): ...
3124 class C1(P1):
3125 def meth(self) -> int:
3126 return 0
3127 B1() # E: Cannot instantiate abstract class "B1" with abstract attribute "meth"
3128 C1()
3129
3130 class P2(Protocol):
3131 @classmethod
3132 def meth(cls) -> int: ...
3133 class B2(P2): ...
3134 class C2(P2):
3135 @classmethod
3136 def meth(cls) -> int:
3137 return 0
3138 B2() # E: Cannot instantiate abstract class "B2" with abstract attribute "meth"
3139 C2()
3140
3141 class P3(Protocol):
3142 @overload
3143 def meth(self, x: int) -> int: ...
3144 @overload
3145 def meth(self, x: str) -> str: ...
3146 @overload
3147 def not_abstract(self, x: int) -> int: ...
3148 @overload
3149 def not_abstract(self, x: str) -> str: ...
3150 def not_abstract(self, x: Union[int, str]) -> Union[int, str]:
3151 return 0
3152 class B3(P3): ...
3153 class C3(P3):
3154 @overload
3155 def meth(self, x: int) -> int: ...
3156 @overload
3157 def meth(self, x: str) -> str: ...
3158 def meth(self, x: Union[int, str]) -> Union[int, str]:
3159 return 0
3160 B3() # E: Cannot instantiate abstract class "B3" with abstract attribute "meth"
3161 C3()
3162 [builtins fixtures/classmethod.pyi]
3163
3164 [case testEmptyBodyImplicitlyAbstractProtocolProperty]
3165 from typing import Protocol
3166
3167 class P1(Protocol):
3168 @property
3169 def attr(self) -> int: ...
3170 class B1(P1): ...
3171 class C1(P1):
3172 @property
3173 def attr(self) -> int:
3174 return 0
3175 B1() # E: Cannot instantiate abstract class "B1" with abstract attribute "attr"
3176 C1()
3177
3178 class P2(Protocol):
3179 @property
3180 def attr(self) -> int: ...
3181 @attr.setter
3182 def attr(self, value: int) -> None: ...
3183 class B2(P2): ...
3184 class C2(P2):
3185 @property
3186 def attr(self) -> int: return 0
3187 @attr.setter
3188 def attr(self, value: int) -> None: pass
3189 B2() # E: Cannot instantiate abstract class "B2" with abstract attribute "attr"
3190 C2()
3191 [builtins fixtures/property.pyi]
3192
3193 [case testEmptyBodyImplicitlyAbstractProtocolStub]
3194 from stub import P1, P2, P3, P4
3195
3196 class B1(P1): ...
3197 class B2(P2): ...
3198 class B3(P3): ...
3199 class B4(P4): ...
3200
3201 B1()
3202 B2()
3203 B3()
3204 B4() # E: Cannot instantiate abstract class "B4" with abstract attribute "meth"
3205
3206 [file stub.pyi]
3207 from typing import Protocol, overload, Union
3208 from abc import abstractmethod
3209
3210 class P1(Protocol):
3211 def meth(self) -> int: ...
3212
3213 class P2(Protocol):
3214 @classmethod
3215 def meth(cls) -> int: ...
3216
3217 class P3(Protocol):
3218 @overload
3219 def meth(self, x: int) -> int: ...
3220 @overload
3221 def meth(self, x: str) -> str: ...
3222
3223 class P4(Protocol):
3224 @abstractmethod
3225 def meth(self) -> int: ...
3226 [builtins fixtures/classmethod.pyi]
3227
3228 [case testEmptyBodyVariationsImplicitlyAbstractProtocol]
3229 from typing import Protocol
3230
3231 class WithPass(Protocol):
3232 def meth(self) -> int:
3233 pass
3234 class A(WithPass): ...
3235 A() # E: Cannot instantiate abstract class "A" with abstract attribute "meth"
3236
3237 class WithEllipses(Protocol):
3238 def meth(self) -> int: ...
3239 class B(WithEllipses): ...
3240 B() # E: Cannot instantiate abstract class "B" with abstract attribute "meth"
3241
3242 class WithDocstring(Protocol):
3243 def meth(self) -> int:
3244 """Docstring for meth.
3245
3246 This is meth."""
3247 class C(WithDocstring): ...
3248 C() # E: Cannot instantiate abstract class "C" with abstract attribute "meth"
3249
3250 class WithRaise(Protocol):
3251 def meth(self) -> int:
3252 """Docstring for meth."""
3253 raise NotImplementedError
3254 class D(WithRaise): ...
3255 D() # E: Cannot instantiate abstract class "D" with abstract attribute "meth"
3256 [builtins fixtures/exception.pyi]
3257
3258 [case testEmptyBodyNoneCompatibleProtocol]
3259 from abc import abstractmethod
3260 from typing import Any, Optional, Protocol, Union, overload
3261 from typing_extensions import TypeAlias
3262
3263 NoneAlias: TypeAlias = None
3264
3265 class NoneCompatible(Protocol):
3266 def f(self) -> None: ...
3267 def g(self) -> Any: ...
3268 def h(self) -> Optional[int]: ...
3269 def i(self) -> NoneAlias: ...
3270 @classmethod
3271 def j(cls) -> None: ...
3272
3273 class A(NoneCompatible): ...
3274 A() # E: Cannot instantiate abstract class "A" with abstract attributes "f", "g", "h", "i" and "j" \
3275 # N: The following methods were marked implicitly abstract because they have empty function bodies: "f", "g", "h", "i" and "j". If they are not meant to be abstract, explicitly `return` or `return None`.
3276
3277 class NoneCompatible2(Protocol):
3278 def f(self, x: int): ...
3279
3280 class B(NoneCompatible2): ...
3281 B() # E: Cannot instantiate abstract class "B" with abstract attribute "f" \
3282 # N: "f" is implicitly abstract because it has an empty function body. If it is not meant to be abstract, explicitly `return` or `return None`.
3283
3284 class NoneCompatible3(Protocol):
3285 @abstractmethod
3286 def f(self) -> None: ...
3287 @overload
3288 def g(self, x: int) -> int: ...
3289 @overload
3290 def g(self, x: str) -> None: ...
3291 def h(self, x): ...
3292
3293 class C(NoneCompatible3): ...
3294 C() # E: Cannot instantiate abstract class "C" with abstract attributes "f", "g" and "h"
3295 [builtins fixtures/classmethod.pyi]
3296
3297 [case testEmptyBodyWithFinal]
3298 from typing import Protocol, final
3299
3300 class P(Protocol):
3301 @final # E: Protocol member cannot be final
3302 def f(self, x: int) -> str: ...
3303
3304 class A(P): ...
3305 A() # E: Cannot instantiate abstract class "A" with abstract attribute "f"
3306
3307 [case testProtocolWithNestedClass]
3308 from typing import TypeVar, Protocol
3309
3310 class Template(Protocol):
3311 var: int
3312 class Meta: ...
3313
3314 class B:
3315 var: int
3316 class Meta: ...
3317 class C:
3318 var: int
3319 class Meta(Template.Meta): ...
3320
3321 def foo(t: Template) -> None: ...
3322 foo(B()) # E: Argument 1 to "foo" has incompatible type "B"; expected "Template" \
3323 # N: Following member(s) of "B" have conflicts: \
3324 # N: Meta: expected "type[__main__.Template.Meta]", got "type[__main__.B.Meta]"
3325 foo(C()) # OK
3326
3327 [case testProtocolClassObjectAttribute]
3328 from typing import ClassVar, Protocol
3329
3330 class P(Protocol):
3331 foo: int
3332
3333 class A:
3334 foo = 42
3335 class B:
3336 foo: ClassVar[int]
3337 class C:
3338 foo: ClassVar[str]
3339 class D:
3340 foo: int
3341
3342 def test(arg: P) -> None: ...
3343 test(A) # OK
3344 test(B) # OK
3345 test(C) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3346 # N: Following member(s) of "C" have conflicts: \
3347 # N: foo: expected "int", got "str"
3348 test(D) # E: Argument 1 to "test" has incompatible type "type[D]"; expected "P" \
3349 # N: Only class variables allowed for class object access on protocols, foo is an instance variable of "D"
3350
3351 [case testProtocolClassObjectClassVarRejected]
3352 from typing import ClassVar, Protocol
3353
3354 class P(Protocol):
3355 foo: ClassVar[int]
3356
3357 class B:
3358 foo: ClassVar[int]
3359
3360 def test(arg: P) -> None: ...
3361 test(B) # E: Argument 1 to "test" has incompatible type "type[B]"; expected "P" \
3362 # N: ClassVar protocol member P.foo can never be matched by a class object
3363
3364 [case testProtocolClassObjectPropertyRejected]
3365 from typing import ClassVar, Protocol
3366
3367 class P(Protocol):
3368 @property
3369 def foo(self) -> int: ...
3370
3371 class B:
3372 @property
3373 def foo(self) -> int: ...
3374 class C:
3375 foo: int
3376 class D:
3377 foo: ClassVar[int]
3378
3379 def test(arg: P) -> None: ...
3380 # TODO: skip type mismatch diagnostics in this case.
3381 test(B) # E: Argument 1 to "test" has incompatible type "type[B]"; expected "P" \
3382 # N: Following member(s) of "B" have conflicts: \
3383 # N: foo: expected "int", got "Callable[[B], int]" \
3384 # N: Only class variables allowed for class object access on protocols, foo is an instance variable of "B"
3385 test(C) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3386 # N: Only class variables allowed for class object access on protocols, foo is an instance variable of "C"
3387 test(D) # OK
3388 [builtins fixtures/property.pyi]
3389
3390 [case testProtocolClassObjectInstanceMethod]
3391 from typing import Any, Protocol
3392
3393 class P(Protocol):
3394 def foo(self, obj: Any) -> int: ...
3395
3396 class B:
3397 def foo(self) -> int: ...
3398 class C:
3399 def foo(self) -> str: ...
3400
3401 def test(arg: P) -> None: ...
3402 test(B) # OK
3403 test(C) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3404 # N: Following member(s) of "C" have conflicts: \
3405 # N: Expected: \
3406 # N: def foo(obj: Any) -> int \
3407 # N: Got: \
3408 # N: def foo(self: C) -> str
3409
3410 [case testProtocolClassObjectInstanceMethodArg]
3411 from typing import Any, Protocol
3412
3413 class P(Protocol):
3414 def foo(self, obj: B) -> int: ...
3415
3416 class B:
3417 def foo(self) -> int: ...
3418 class C:
3419 def foo(self) -> int: ...
3420
3421 def test(arg: P) -> None: ...
3422 test(B) # OK
3423 test(C) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3424 # N: Following member(s) of "C" have conflicts: \
3425 # N: Expected: \
3426 # N: def foo(obj: B) -> int \
3427 # N: Got: \
3428 # N: def foo(self: C) -> int
3429
3430 [case testProtocolClassObjectInstanceMethodOverloaded]
3431 from typing import Any, Protocol, overload
3432
3433 class P(Protocol):
3434 @overload
3435 def foo(self, obj: Any, arg: int) -> int: ...
3436 @overload
3437 def foo(self, obj: Any, arg: str) -> str: ...
3438
3439 class B:
3440 @overload
3441 def foo(self, arg: int) -> int: ...
3442 @overload
3443 def foo(self, arg: str) -> str: ...
3444 def foo(self, arg: Any) -> Any:
3445 ...
3446
3447 class C:
3448 @overload
3449 def foo(self, arg: int) -> int: ...
3450 @overload
3451 def foo(self, arg: str) -> int: ...
3452 def foo(self, arg: Any) -> Any:
3453 ...
3454
3455 def test(arg: P) -> None: ...
3456 test(B) # OK
3457 test(C) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3458 # N: Following member(s) of "C" have conflicts: \
3459 # N: Expected: \
3460 # N: @overload \
3461 # N: def foo(obj: Any, arg: int) -> int \
3462 # N: @overload \
3463 # N: def foo(obj: Any, arg: str) -> str \
3464 # N: Got: \
3465 # N: @overload \
3466 # N: def foo(self: C, arg: int) -> int \
3467 # N: @overload \
3468 # N: def foo(self: C, arg: str) -> int
3469
3470 [case testProtocolClassObjectClassMethod]
3471 from typing import Protocol
3472
3473 class P(Protocol):
3474 def foo(self) -> int: ...
3475
3476 class B:
3477 @classmethod
3478 def foo(cls) -> int: ...
3479 class C:
3480 @classmethod
3481 def foo(cls) -> str: ...
3482
3483 def test(arg: P) -> None: ...
3484 test(B) # OK
3485 test(C) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3486 # N: Following member(s) of "C" have conflicts: \
3487 # N: Expected: \
3488 # N: def foo() -> int \
3489 # N: Got: \
3490 # N: def foo() -> str
3491 [builtins fixtures/classmethod.pyi]
3492
3493 [case testProtocolClassObjectStaticMethod]
3494 from typing import Protocol
3495
3496 class P(Protocol):
3497 def foo(self) -> int: ...
3498
3499 class B:
3500 @staticmethod
3501 def foo() -> int: ...
3502 class C:
3503 @staticmethod
3504 def foo() -> str: ...
3505
3506 def test(arg: P) -> None: ...
3507 test(B) # OK
3508 test(C) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3509 # N: Following member(s) of "C" have conflicts: \
3510 # N: Expected: \
3511 # N: def foo() -> int \
3512 # N: Got: \
3513 # N: def foo() -> str
3514 [builtins fixtures/staticmethod.pyi]
3515
3516 [case testProtocolClassObjectGenericInstanceMethod]
3517 from typing import Any, Protocol, Generic, List, TypeVar
3518
3519 class P(Protocol):
3520 def foo(self, obj: Any) -> List[int]: ...
3521
3522 T = TypeVar("T")
3523 class A(Generic[T]):
3524 def foo(self) -> T: ...
3525 class AA(A[List[T]]): ...
3526
3527 class B(AA[int]): ...
3528 class C(AA[str]): ...
3529
3530 def test(arg: P) -> None: ...
3531 test(B) # OK
3532 test(C) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3533 # N: Following member(s) of "C" have conflicts: \
3534 # N: Expected: \
3535 # N: def foo(obj: Any) -> list[int] \
3536 # N: Got: \
3537 # N: def foo(self: A[list[str]]) -> list[str]
3538 [builtins fixtures/list.pyi]
3539
3540 [case testProtocolClassObjectGenericClassMethod]
3541 from typing import Any, Protocol, Generic, List, TypeVar
3542
3543 class P(Protocol):
3544 def foo(self) -> List[int]: ...
3545
3546 T = TypeVar("T")
3547 class A(Generic[T]):
3548 @classmethod
3549 def foo(self) -> T: ...
3550 class AA(A[List[T]]): ...
3551
3552 class B(AA[int]): ...
3553 class C(AA[str]): ...
3554
3555 def test(arg: P) -> None: ...
3556 test(B) # OK
3557 test(C) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3558 # N: Following member(s) of "C" have conflicts: \
3559 # N: Expected: \
3560 # N: def foo() -> list[int] \
3561 # N: Got: \
3562 # N: def foo() -> list[str]
3563 [builtins fixtures/isinstancelist.pyi]
3564
3565 [case testProtocolClassObjectSelfTypeInstanceMethod]
3566 from typing import Protocol, TypeVar, Union
3567
3568 T = TypeVar("T")
3569 class P(Protocol):
3570 def foo(self, arg: T) -> T: ...
3571
3572 class B:
3573 def foo(self: T) -> T: ...
3574 class C:
3575 def foo(self: T) -> Union[T, int]: ...
3576
3577 def test(arg: P) -> None: ...
3578 test(B) # OK
3579 test(C) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3580 # N: Following member(s) of "C" have conflicts: \
3581 # N: Expected: \
3582 # N: def [T] foo(arg: T) -> T \
3583 # N: Got: \
3584 # N: def [T] foo(self: T) -> T | int
3585
3586 [case testProtocolClassObjectSelfTypeClassMethod]
3587 from typing import Protocol, Type, TypeVar
3588
3589 T = TypeVar("T")
3590 class P(Protocol):
3591 def foo(self) -> B: ...
3592
3593 class B:
3594 @classmethod
3595 def foo(cls: Type[T]) -> T: ...
3596 class C:
3597 @classmethod
3598 def foo(cls: Type[T]) -> T: ...
3599
3600 def test(arg: P) -> None: ...
3601 test(B) # OK
3602 test(C) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3603 # N: Following member(s) of "C" have conflicts: \
3604 # N: Expected: \
3605 # N: def foo() -> B \
3606 # N: Got: \
3607 # N: def foo() -> C
3608 [builtins fixtures/classmethod.pyi]
3609
3610 [case testProtocolClassObjectAttributeAndCall]
3611 from typing import Any, ClassVar, Protocol
3612
3613 class P(Protocol):
3614 foo: int
3615 def __call__(self, x: int, y: int) -> Any: ...
3616
3617 class B:
3618 foo: ClassVar[int]
3619 def __init__(self, x: int, y: int) -> None: ...
3620 class C:
3621 foo: ClassVar[int]
3622 def __init__(self, x: int, y: str) -> None: ...
3623
3624 def test(arg: P) -> None: ...
3625 test(B) # OK
3626 test(C) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3627 # N: "C" has constructor incompatible with "__call__" of "P" \
3628 # N: Following member(s) of "C" have conflicts: \
3629 # N: Expected: \
3630 # N: def __call__(x: int, y: int) -> Any \
3631 # N: Got: \
3632 # N: def C(x: int, y: str) -> C \
3633 # N: "P.__call__" has type "def __call__(self, x: int, y: int) -> Any"
3634
3635 [case testProtocolClassObjectPureCallback]
3636 from typing import Any, ClassVar, Protocol
3637
3638 class P(Protocol):
3639 def __call__(self, x: int, y: int) -> Any: ...
3640
3641 class B:
3642 def __init__(self, x: int, y: int) -> None: ...
3643 class C:
3644 def __init__(self, x: int, y: str) -> None: ...
3645
3646 def test(arg: P) -> None: ...
3647 test(B) # OK
3648 test(C) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3649 # N: "C" has constructor incompatible with "__call__" of "P" \
3650 # N: Following member(s) of "C" have conflicts: \
3651 # N: Expected: \
3652 # N: def __call__(x: int, y: int) -> Any \
3653 # N: Got: \
3654 # N: def C(x: int, y: str) -> C \
3655 # N: "P.__call__" has type "def __call__(self, x: int, y: int) -> Any"
3656 [builtins fixtures/type.pyi]
3657
3658 [case testProtocolClassObjectCallableError]
3659 from typing import Protocol, Any, Callable
3660
3661 class P(Protocol):
3662 def __call__(self, app: int) -> Callable[[str], None]:
3663 ...
3664
3665 class C:
3666 def __init__(self, app: str) -> None:
3667 pass
3668
3669 def __call__(self, el: str) -> None:
3670 return None
3671
3672 p: P = C # E: Incompatible types in assignment (expression has type "type[C]", variable has type "P") \
3673 # N: Following member(s) of "C" have conflicts: \
3674 # N: Expected: \
3675 # N: def __call__(app: int) -> Callable[[str], None] \
3676 # N: Got: \
3677 # N: def C(app: str) -> C \
3678 # N: "P.__call__" has type "def __call__(self, app: int) -> Callable[[str], None]"
3679
3680 [builtins fixtures/type.pyi]
3681
3682 [case testProtocolTypeTypeAttribute]
3683 from typing import ClassVar, Protocol, Type
3684
3685 class P(Protocol):
3686 foo: int
3687
3688 class A:
3689 foo = 42
3690 class B:
3691 foo: ClassVar[int]
3692 class C:
3693 foo: ClassVar[str]
3694 class D:
3695 foo: int
3696
3697 def test(arg: P) -> None: ...
3698 a: Type[A]
3699 b: Type[B]
3700 c: Type[C]
3701 d: Type[D]
3702 test(a) # OK
3703 test(b) # OK
3704 test(c) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3705 # N: Following member(s) of "C" have conflicts: \
3706 # N: foo: expected "int", got "str"
3707 test(d) # E: Argument 1 to "test" has incompatible type "type[D]"; expected "P" \
3708 # N: Only class variables allowed for class object access on protocols, foo is an instance variable of "D"
3709
3710 [case testProtocolTypeTypeInstanceMethod]
3711 from typing import Any, Protocol, Type
3712
3713 class P(Protocol):
3714 def foo(self, cls: Any) -> int: ...
3715
3716 class B:
3717 def foo(self) -> int: ...
3718 class C:
3719 def foo(self) -> str: ...
3720
3721 def test(arg: P) -> None: ...
3722 b: Type[B]
3723 c: Type[C]
3724 test(b) # OK
3725 test(c) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3726 # N: Following member(s) of "C" have conflicts: \
3727 # N: Expected: \
3728 # N: def foo(cls: Any) -> int \
3729 # N: Got: \
3730 # N: def foo(self: C) -> str
3731
3732 [case testProtocolTypeTypeClassMethod]
3733 from typing import Protocol, Type
3734
3735 class P(Protocol):
3736 def foo(self) -> int: ...
3737
3738 class B:
3739 @classmethod
3740 def foo(cls) -> int: ...
3741 class C:
3742 @classmethod
3743 def foo(cls) -> str: ...
3744
3745 def test(arg: P) -> None: ...
3746 b: Type[B]
3747 c: Type[C]
3748 test(b) # OK
3749 test(c) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3750 # N: Following member(s) of "C" have conflicts: \
3751 # N: Expected: \
3752 # N: def foo() -> int \
3753 # N: Got: \
3754 # N: def foo() -> str
3755 [builtins fixtures/classmethod.pyi]
3756
3757 [case testProtocolTypeTypeSelfTypeInstanceMethod]
3758 from typing import Protocol, Type, TypeVar, Union
3759
3760 T = TypeVar("T")
3761 class P(Protocol):
3762 def foo(self, arg: T) -> T: ...
3763
3764 class B:
3765 def foo(self: T) -> T: ...
3766 class C:
3767 def foo(self: T) -> Union[T, int]: ...
3768
3769 def test(arg: P) -> None: ...
3770 b: Type[B]
3771 c: Type[C]
3772 test(b) # OK
3773 test(c) # E: Argument 1 to "test" has incompatible type "type[C]"; expected "P" \
3774 # N: Following member(s) of "C" have conflicts: \
3775 # N: Expected: \
3776 # N: def [T] foo(arg: T) -> T \
3777 # N: Got: \
3778 # N: def [T] foo(self: T) -> T | int
3779
3780 [case testProtocolClassObjectInference]
3781 from typing import Any, Protocol, TypeVar
3782
3783 T = TypeVar("T", contravariant=True)
3784 class P(Protocol[T]):
3785 def foo(self, obj: T) -> int: ...
3786
3787 class B:
3788 def foo(self) -> int: ...
3789
3790 S = TypeVar("S")
3791 def test(arg: P[S]) -> S: ...
3792 reveal_type(test(B)) # N: Revealed type is "__main__.B"
3793
3794 [case testProtocolTypeTypeInference]
3795 from typing import Any, Protocol, TypeVar, Type
3796
3797 T = TypeVar("T", contravariant=True)
3798 class P(Protocol[T]):
3799 def foo(self, obj: T) -> int: ...
3800
3801 class B:
3802 def foo(self) -> int: ...
3803
3804 S = TypeVar("S")
3805 def test(arg: P[S]) -> S: ...
3806 b: Type[B]
3807 reveal_type(test(b)) # N: Revealed type is "__main__.B"
3808
3809 [case testTypeAliasInProtocolBody]
3810 from typing import Protocol, List
3811
3812 class P(Protocol):
3813 x = List[str] # E: Type aliases are prohibited in protocol bodies \
3814 # N: Use variable annotation syntax to define protocol members
3815
3816 class C:
3817 x: int
3818 def foo(x: P) -> None: ...
3819 foo(C()) # No extra error here
3820 [builtins fixtures/list.pyi]
3821
3822 [case testTypeVarInProtocolBody]
3823 from typing import Protocol, TypeVar
3824
3825 class C(Protocol):
3826 T = TypeVar('T')
3827 def __call__(self, t: T) -> T: ...
3828
3829 def f_bad(t: int) -> int:
3830 return t
3831
3832 S = TypeVar("S")
3833 def f_good(t: S) -> S:
3834 return t
3835
3836 g: C = f_bad # E: Incompatible types in assignment (expression has type "Callable[[int], int]", variable has type "C") \
3837 # N: "C.__call__" has type "def [T] __call__(self, t: T) -> T"
3838 g = f_good # OK
3839
3840 [case testModuleAsProtocolImplementation]
3841 import default_config
3842 import bad_config_1
3843 import bad_config_2
3844 import bad_config_3
3845 from typing import Protocol
3846
3847 class Options(Protocol):
3848 timeout: int
3849 one_flag: bool
3850 other_flag: bool
3851 def update(self) -> bool: ...
3852
3853 def setup(options: Options) -> None: ...
3854 setup(default_config) # OK
3855 setup(bad_config_1) # E: Argument 1 to "setup" has incompatible type Module; expected "Options" \
3856 # N: "ModuleType" is missing following "Options" protocol member: \
3857 # N: timeout
3858 setup(bad_config_2) # E: Argument 1 to "setup" has incompatible type Module; expected "Options" \
3859 # N: Following member(s) of Module "bad_config_2" have conflicts: \
3860 # N: one_flag: expected "bool", got "int"
3861 setup(bad_config_3) # E: Argument 1 to "setup" has incompatible type Module; expected "Options" \
3862 # N: Following member(s) of Module "bad_config_3" have conflicts: \
3863 # N: Expected: \
3864 # N: def update() -> bool \
3865 # N: Got: \
3866 # N: def update(obj: Any) -> bool
3867
3868 [file default_config.py]
3869 timeout = 100
3870 one_flag = True
3871 other_flag = False
3872 def update() -> bool: ...
3873
3874 [file bad_config_1.py]
3875 one_flag = True
3876 other_flag = False
3877 def update() -> bool: ...
3878
3879 [file bad_config_2.py]
3880 timeout = 100
3881 one_flag = 42
3882 other_flag = False
3883 def update() -> bool: ...
3884
3885 [file bad_config_3.py]
3886 timeout = 100
3887 one_flag = True
3888 other_flag = False
3889 def update(obj) -> bool: ...
3890 [builtins fixtures/module.pyi]
3891
3892 [case testModuleAsProtocolImplementationInference]
3893 import default_config
3894 from typing import Protocol, TypeVar
3895
3896 T = TypeVar("T", covariant=True)
3897 class Options(Protocol[T]):
3898 timeout: int
3899 one_flag: bool
3900 other_flag: bool
3901 def update(self) -> T: ...
3902
3903 def setup(options: Options[T]) -> T: ...
3904 reveal_type(setup(default_config)) # N: Revealed type is "builtins.str"
3905
3906 [file default_config.py]
3907 timeout = 100
3908 one_flag = True
3909 other_flag = False
3910 def update() -> str: ...
3911 [builtins fixtures/module.pyi]
3912
3913 [case testModuleAsProtocolImplementationClassObject]
3914 import runner
3915 import bad_runner
3916 from typing import Callable, Protocol
3917
3918 class Runner(Protocol):
3919 @property
3920 def Run(self) -> Callable[[int], Result]: ...
3921
3922 class Result(Protocol):
3923 value: int
3924
3925 def run(x: Runner) -> None: ...
3926 run(runner) # OK
3927 run(bad_runner) # E: Argument 1 to "run" has incompatible type Module; expected "Runner" \
3928 # N: Following member(s) of Module "bad_runner" have conflicts: \
3929 # N: Expected: \
3930 # N: def (int, /) -> Result \
3931 # N: Got: \
3932 # N: def Run(arg: str) -> Run
3933
3934 [file runner.py]
3935 class Run:
3936 value: int
3937 def __init__(self, arg: int) -> None: ...
3938
3939 [file bad_runner.py]
3940 class Run:
3941 value: int
3942 def __init__(self, arg: str) -> None: ...
3943 [builtins fixtures/module.pyi]
3944
3945 [case testModuleAsProtocolImplementationTypeAlias]
3946 import runner
3947 import bad_runner
3948 from typing import Callable, Protocol
3949
3950 class Runner(Protocol):
3951 @property
3952 def run(self) -> Callable[[int], Result]: ...
3953
3954 class Result(Protocol):
3955 value: int
3956
3957 def run(x: Runner) -> None: ...
3958 run(runner) # OK
3959 run(bad_runner) # E: Argument 1 to "run" has incompatible type Module; expected "Runner" \
3960 # N: Following member(s) of Module "bad_runner" have conflicts: \
3961 # N: Expected: \
3962 # N: def (int, /) -> Result \
3963 # N: Got: \
3964 # N: def Run(arg: str) -> Run
3965
3966 [file runner.py]
3967 class Run:
3968 value: int
3969 def __init__(self, arg: int) -> None: ...
3970 run = Run
3971
3972 [file bad_runner.py]
3973 class Run:
3974 value: int
3975 def __init__(self, arg: str) -> None: ...
3976 run = Run
3977 [builtins fixtures/module.pyi]
3978
3979 [case testModuleAsProtocolImplementationClassVar]
3980 from typing import ClassVar, Protocol
3981 import mod
3982
3983 class My(Protocol):
3984 x: ClassVar[int]
3985
3986 def test(mod: My) -> None: ...
3987 test(mod=mod) # E: Argument "mod" to "test" has incompatible type Module; expected "My" \
3988 # N: Protocol member My.x expected class variable, got instance variable
3989 [file mod.py]
3990 x: int
3991 [builtins fixtures/module.pyi]
3992
3993 [case testModuleAsProtocolImplementationFinal]
3994 from typing import Protocol
3995 import some_module
3996
3997 class My(Protocol):
3998 a: int
3999
4000 def func(arg: My) -> None: ...
4001 func(some_module) # E: Argument 1 to "func" has incompatible type Module; expected "My" \
4002 # N: Protocol member My.a expected settable variable, got read-only attribute
4003
4004 [file some_module.py]
4005 from typing import Final
4006
4007 a: Final = 1
4008 [builtins fixtures/module.pyi]
4009
4010
4011 [case testModuleAsProtocolRedefinitionTopLevel]
4012 from typing import Protocol
4013
4014 class P(Protocol):
4015 def f(self) -> str: ...
4016
4017 cond: bool
4018 t: P
4019 if cond:
4020 import mod1 as t
4021 else:
4022 import mod2 as t
4023
4024 import badmod as t # E: Incompatible import of "t" (imported name has type Module, local name has type "P")
4025
4026 [file mod1.py]
4027 def f() -> str: ...
4028
4029 [file mod2.py]
4030 def f() -> str: ...
4031
4032 [file badmod.py]
4033 def nothing() -> int: ...
4034 [builtins fixtures/module.pyi]
4035
4036 [case testModuleAsProtocolRedefinitionImportFrom]
4037 from typing import Protocol
4038
4039 class P(Protocol):
4040 def f(self) -> str: ...
4041
4042 cond: bool
4043 t: P
4044 if cond:
4045 from package import mod1 as t
4046 else:
4047 from package import mod2 as t
4048
4049 from package import badmod as t # E: Incompatible import of "t" (imported name has type Module, local name has type "P")
4050
4051 package: int = 10
4052
4053 import package.mod1 as t
4054 import package.mod1 # E: Incompatible import of "package" (imported name has type Module, local name has type "int")
4055
4056 [file package/mod1.py]
4057 def f() -> str: ...
4058
4059 [file package/mod2.py]
4060 def f() -> str: ...
4061
4062 [file package/badmod.py]
4063 def nothing() -> int: ...
4064 [builtins fixtures/module.pyi]
4065
4066 [case testProtocolSelfTypeNewSyntax]
4067 from typing import Protocol, Self
4068
4069 class P(Protocol):
4070 @property
4071 def next(self) -> Self: ...
4072
4073 class C:
4074 next: C
4075 class S:
4076 next: Self
4077
4078 x: P = C()
4079 y: P = S()
4080
4081 z: P
4082 reveal_type(S().next) # N: Revealed type is "__main__.S"
4083 reveal_type(z.next) # N: Revealed type is "__main__.P"
4084 [builtins fixtures/property.pyi]
4085
4086 [case testProtocolSelfTypeNewSyntaxSubProtocol]
4087 from typing import Protocol, Self
4088
4089 class P(Protocol):
4090 @property
4091 def next(self) -> Self: ...
4092 class PS(P, Protocol):
4093 @property
4094 def other(self) -> Self: ...
4095
4096 class C:
4097 next: C
4098 other: C
4099 class S:
4100 next: Self
4101 other: Self
4102
4103 x: PS = C()
4104 y: PS = S()
4105 [builtins fixtures/property.pyi]
4106
4107 [case testProtocolClassVarSelfType]
4108 from typing import ClassVar, Self, Protocol
4109
4110 class P(Protocol):
4111 DEFAULT: ClassVar[Self]
4112 class C:
4113 DEFAULT: ClassVar[C]
4114
4115 x: P = C()
4116
4117 [case testInferenceViaTypeTypeMetaclass]
4118 from typing import Iterator, Iterable, TypeVar, Type
4119
4120 M = TypeVar("M")
4121
4122 class Meta(type):
4123 def __iter__(self: Type[M]) -> Iterator[M]: ...
4124 class Foo(metaclass=Meta): ...
4125
4126 T = TypeVar("T")
4127 def test(x: Iterable[T]) -> T: ...
4128
4129 reveal_type(test(Foo)) # N: Revealed type is "__main__.Foo"
4130 t_foo: Type[Foo]
4131 reveal_type(test(t_foo)) # N: Revealed type is "__main__.Foo"
4132
4133 TF = TypeVar("TF", bound=Foo)
4134 def outer(cls: Type[TF]) -> TF:
4135 reveal_type(test(cls)) # N: Revealed type is "TF`-1"
4136 return cls()
4137
4138 [case testProtocolImportNotMember]
4139 import m
4140 import lib
4141
4142 class Bad:
4143 x: int
4144 class Good:
4145 x: lib.C
4146
4147 x: m.P = Bad() # E: Incompatible types in assignment (expression has type "Bad", variable has type "P") \
4148 # N: Following member(s) of "Bad" have conflicts: \
4149 # N: x: expected "C", got "int"
4150 x = Good()
4151
4152 [file m.py]
4153 from typing import Protocol
4154
4155 class P(Protocol):
4156 import lib
4157 x: lib.C
4158
4159 [file lib.py]
4160 class C: ...
4161
4162 [case testAllowDefaultConstructorInProtocols]
4163 from typing import Protocol
4164
4165 class P(Protocol):
4166 x: int
4167 def __init__(self, x: int) -> None:
4168 self.x = x
4169
4170 class C(P): ...
4171 C(0) # OK
4172
4173 [case testTypeVarValueConstraintAgainstGenericProtocol]
4174 from typing import TypeVar, Generic, Protocol, overload
4175
4176 T_contra = TypeVar("T_contra", contravariant=True)
4177 AnyStr = TypeVar("AnyStr", str, bytes)
4178
4179 class SupportsWrite(Protocol[T_contra]):
4180 def write(self, s: T_contra, /) -> None: ...
4181
4182 class Buffer: ...
4183
4184 class IO(Generic[AnyStr]):
4185 @overload
4186 def write(self: IO[bytes], s: Buffer, /) -> None: ...
4187 @overload
4188 def write(self, s: AnyStr, /) -> None: ...
4189 def write(self, s): ...
4190
4191 def foo(fdst: SupportsWrite[AnyStr]) -> None: ...
4192
4193 x: IO[str]
4194 foo(x)
4195
4196 [case testTypeVarValueConstraintAgainstGenericProtocol2]
4197 from typing import Generic, Protocol, TypeVar, overload
4198
4199 AnyStr = TypeVar("AnyStr", str, bytes)
4200 T_co = TypeVar("T_co", covariant=True)
4201 T_contra = TypeVar("T_contra", contravariant=True)
4202
4203 class SupportsRead(Generic[T_co]):
4204 def read(self) -> T_co: ...
4205
4206 class SupportsWrite(Protocol[T_contra]):
4207 def write(self, s: T_contra) -> object: ...
4208
4209 def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr]) -> None: ...
4210
4211 class WriteToMe(Generic[AnyStr]):
4212 @overload
4213 def write(self: WriteToMe[str], s: str) -> int: ...
4214 @overload
4215 def write(self: WriteToMe[bytes], s: bytes) -> int: ...
4216 def write(self, s): ...
4217
4218 class WriteToMeOrReadFromMe(WriteToMe[AnyStr], SupportsRead[AnyStr]): ...
4219
4220 copyfileobj(WriteToMeOrReadFromMe[bytes](), WriteToMe[bytes]())
4221
4222 [case testOverloadedMethodWithExplicitSelfTypes]
4223 from typing import Generic, overload, Protocol, TypeVar, Union
4224
4225 AnyStr = TypeVar("AnyStr", str, bytes)
4226 T_co = TypeVar("T_co", covariant=True)
4227 T_contra = TypeVar("T_contra", contravariant=True)
4228
4229 class SupportsRead(Protocol[T_co]):
4230 def read(self) -> T_co: ...
4231
4232 class SupportsWrite(Protocol[T_contra]):
4233 def write(self, s: T_contra) -> int: ...
4234
4235 class Input(Generic[AnyStr]):
4236 def read(self) -> AnyStr: ...
4237
4238 class Output(Generic[AnyStr]):
4239 @overload
4240 def write(self: Output[str], s: str) -> int: ...
4241 @overload
4242 def write(self: Output[bytes], s: bytes) -> int: ...
4243 def write(self, s: Union[str, bytes]) -> int: ...
4244
4245 def f(src: SupportsRead[AnyStr], dst: SupportsWrite[AnyStr]) -> None: ...
4246
4247 def g1(a: Input[bytes], b: Output[bytes]) -> None:
4248 f(a, b)
4249
4250 def g2(a: Input[bytes], b: Output[bytes]) -> None:
4251 f(a, b)
4252
4253 def g3(a: Input[str], b: Output[bytes]) -> None:
4254 f(a, b) # E: Cannot infer value of type parameter "AnyStr" of "f"
4255
4256 def g4(a: Input[bytes], b: Output[str]) -> None:
4257 f(a, b) # E: Cannot infer value of type parameter "AnyStr" of "f"
4258
4259 [builtins fixtures/tuple.pyi]
4260
4261 [case testOverloadProtocolSubtyping]
4262 from typing import Protocol, Self, overload
4263
4264 class NumpyFloat:
4265 __add__: "FloatOP"
4266
4267 class FloatOP(Protocol):
4268 @overload
4269 def __call__(self, other: float) -> NumpyFloat: ...
4270 @overload
4271 def __call__(self, other: NumpyFloat) -> NumpyFloat: ...
4272
4273 class SupportsAdd(Protocol):
4274 @overload
4275 def __add__(self, other: float) -> Self: ...
4276 @overload
4277 def __add__(self, other: NumpyFloat) -> Self: ...
4278
4279 x: SupportsAdd = NumpyFloat()
4280 [builtins fixtures/tuple.pyi]
4281
4282 [case testSetterPropertyProtocolSubtypingBoth]
4283 from typing import Protocol
4284
4285 class B1: ...
4286 class C1(B1): ...
4287 class B2: ...
4288 class C2(B2): ...
4289
4290 class P1(Protocol):
4291 @property
4292 def foo(self) -> B1: ...
4293 @foo.setter
4294 def foo(self, x: C2) -> None: ...
4295
4296 class P2(Protocol):
4297 @property
4298 def foo(self) -> B1: ...
4299 @foo.setter
4300 def foo(self, x: B2) -> None: ...
4301
4302 class A1:
4303 @property
4304 def foo(self) -> B1: ...
4305 @foo.setter
4306 def foo(self, x: C2) -> None: ...
4307
4308 class A2:
4309 @property
4310 def foo(self) -> C1: ...
4311 @foo.setter
4312 def foo(self, x: C2) -> None: ...
4313
4314 class A3:
4315 @property
4316 def foo(self) -> C1: ...
4317 @foo.setter
4318 def foo(self, x: str) -> None: ...
4319
4320 class A4:
4321 @property
4322 def foo(self) -> str: ...
4323 @foo.setter
4324 def foo(self, x: str) -> None: ...
4325
4326 def f1(x: P1) -> None: ...
4327 def f2(x: P2) -> None: ...
4328
4329 a1: A1
4330 a2: A2
4331 a3: A3
4332 a4: A4
4333
4334 f1(a1)
4335 f1(a2)
4336 f1(a3) # E: Argument 1 to "f1" has incompatible type "A3"; expected "P1" \
4337 # N: Following member(s) of "A3" have conflicts: \
4338 # N: foo: expected setter type "C2", got "str"
4339 f1(a4) # E: Argument 1 to "f1" has incompatible type "A4"; expected "P1" \
4340 # N: Following member(s) of "A4" have conflicts: \
4341 # N: foo: expected "B1", got "str" \
4342 # N: foo: expected setter type "C2", got "str"
4343
4344 f2(a1) # E: Argument 1 to "f2" has incompatible type "A1"; expected "P2" \
4345 # N: Following member(s) of "A1" have conflicts: \
4346 # N: foo: expected setter type "B2", got "C2" \
4347 # N: Setter types should behave contravariantly
4348 f2(a2) # E: Argument 1 to "f2" has incompatible type "A2"; expected "P2" \
4349 # N: Following member(s) of "A2" have conflicts: \
4350 # N: foo: expected setter type "B2", got "C2" \
4351 # N: Setter types should behave contravariantly
4352 f2(a3) # E: Argument 1 to "f2" has incompatible type "A3"; expected "P2" \
4353 # N: Following member(s) of "A3" have conflicts: \
4354 # N: foo: expected setter type "B2", got "str"
4355 f2(a4) # E: Argument 1 to "f2" has incompatible type "A4"; expected "P2" \
4356 # N: Following member(s) of "A4" have conflicts: \
4357 # N: foo: expected "B1", got "str" \
4358 # N: foo: expected setter type "B2", got "str"
4359 [builtins fixtures/property.pyi]
4360
4361 [case testSetterPropertyProtocolSubtypingVarSuper]
4362 from typing import Protocol
4363
4364 class B1: ...
4365 class C1(B1): ...
4366
4367 class P1(Protocol):
4368 foo: B1
4369
4370 class P2(Protocol):
4371 foo: C1
4372
4373 class A1:
4374 @property
4375 def foo(self) -> B1: ...
4376 @foo.setter
4377 def foo(self, x: C1) -> None: ...
4378
4379 class A2:
4380 @property
4381 def foo(self) -> C1: ...
4382 @foo.setter
4383 def foo(self, x: B1) -> None: ...
4384
4385 class A3:
4386 @property
4387 def foo(self) -> C1: ...
4388 @foo.setter
4389 def foo(self, x: str) -> None: ...
4390
4391 class A4:
4392 @property
4393 def foo(self) -> str: ...
4394 @foo.setter
4395 def foo(self, x: str) -> None: ...
4396
4397 def f1(x: P1) -> None: ...
4398 def f2(x: P2) -> None: ...
4399
4400 a1: A1
4401 a2: A2
4402 a3: A3
4403 a4: A4
4404
4405 f1(a1) # E: Argument 1 to "f1" has incompatible type "A1"; expected "P1" \
4406 # N: Following member(s) of "A1" have conflicts: \
4407 # N: foo: expected setter type "B1", got "C1" \
4408 # N: Setter types should behave contravariantly
4409 f1(a2)
4410 f1(a3) # E: Argument 1 to "f1" has incompatible type "A3"; expected "P1" \
4411 # N: Following member(s) of "A3" have conflicts: \
4412 # N: foo: expected setter type "B1", got "str"
4413 f1(a4) # E: Argument 1 to "f1" has incompatible type "A4"; expected "P1" \
4414 # N: Following member(s) of "A4" have conflicts: \
4415 # N: foo: expected "B1", got "str"
4416
4417 f2(a1) # E: Argument 1 to "f2" has incompatible type "A1"; expected "P2" \
4418 # N: Following member(s) of "A1" have conflicts: \
4419 # N: foo: expected "C1", got "B1"
4420 f2(a2)
4421 f2(a3) # E: Argument 1 to "f2" has incompatible type "A3"; expected "P2" \
4422 # N: Following member(s) of "A3" have conflicts: \
4423 # N: foo: expected setter type "C1", got "str"
4424 f2(a4) # E: Argument 1 to "f2" has incompatible type "A4"; expected "P2" \
4425 # N: Following member(s) of "A4" have conflicts: \
4426 # N: foo: expected "C1", got "str"
4427 [builtins fixtures/property.pyi]
4428
4429 [case testSetterPropertyProtocolSubtypingVarSub]
4430 from typing import Protocol
4431
4432 class B1: ...
4433 class C1(B1): ...
4434 class B2: ...
4435 class C2(B2): ...
4436
4437 class P1(Protocol):
4438 @property
4439 def foo(self) -> B1: ...
4440 @foo.setter
4441 def foo(self, x: C2) -> None: ...
4442
4443 class P2(Protocol):
4444 @property
4445 def foo(self) -> B1: ...
4446 @foo.setter
4447 def foo(self, x: C1) -> None: ...
4448
4449 class A1:
4450 foo: B1
4451
4452 class A2:
4453 foo: B2
4454
4455 class A3:
4456 foo: C2
4457
4458 class A4:
4459 foo: str
4460
4461 def f1(x: P1) -> None: ...
4462 def f2(x: P2) -> None: ...
4463
4464 a1: A1
4465 a2: A2
4466 a3: A3
4467 a4: A4
4468
4469 f1(a1) # E: Argument 1 to "f1" has incompatible type "A1"; expected "P1" \
4470 # N: Following member(s) of "A1" have conflicts: \
4471 # N: foo: expected setter type "C2", got "B1"
4472 f1(a2) # E: Argument 1 to "f1" has incompatible type "A2"; expected "P1" \
4473 # N: Following member(s) of "A2" have conflicts: \
4474 # N: foo: expected "B1", got "B2"
4475 f1(a3) # E: Argument 1 to "f1" has incompatible type "A3"; expected "P1" \
4476 # N: Following member(s) of "A3" have conflicts: \
4477 # N: foo: expected "B1", got "C2"
4478 f1(a4) # E: Argument 1 to "f1" has incompatible type "A4"; expected "P1" \
4479 # N: Following member(s) of "A4" have conflicts: \
4480 # N: foo: expected "B1", got "str" \
4481 # N: foo: expected setter type "C2", got "str"
4482
4483 f2(a1)
4484 f2(a2) # E: Argument 1 to "f2" has incompatible type "A2"; expected "P2" \
4485 # N: Following member(s) of "A2" have conflicts: \
4486 # N: foo: expected "B1", got "B2" \
4487 # N: foo: expected setter type "C1", got "B2"
4488 f2(a3) # E: Argument 1 to "f2" has incompatible type "A3"; expected "P2" \
4489 # N: Following member(s) of "A3" have conflicts: \
4490 # N: foo: expected "B1", got "C2" \
4491 # N: foo: expected setter type "C1", got "C2"
4492 f2(a4) # E: Argument 1 to "f2" has incompatible type "A4"; expected "P2" \
4493 # N: Following member(s) of "A4" have conflicts: \
4494 # N: foo: expected "B1", got "str" \
4495 # N: foo: expected setter type "C1", got "str"
4496 [builtins fixtures/property.pyi]
4497
4498
4499 [case testExplicitProtocolJoinPreference]
4500 from typing import Protocol, TypeVar
4501
4502 T = TypeVar("T")
4503
4504 class Proto1(Protocol):
4505 def foo(self) -> int: ...
4506 class Proto2(Proto1):
4507 def bar(self) -> str: ...
4508 class Proto3(Proto2):
4509 def baz(self) -> str: ...
4510
4511 class Base: ...
4512
4513 class A(Base, Proto3): ...
4514 class B(Base, Proto3): ...
4515
4516 def join(a: T, b: T) -> T: ...
4517
4518 def main(a: A, b: B) -> None:
4519 reveal_type(join(a, b)) # N: Revealed type is "__main__.Proto3"
4520 reveal_type(join(b, a)) # N: Revealed type is "__main__.Proto3"
4521
4522 [case testProtocolImplementationWithDescriptors]
4523 from typing import Any, Protocol
4524
4525 class Descr:
4526 def __get__(self, inst: Any, owner: Any) -> int: ...
4527
4528 class DescrBad:
4529 def __get__(self, inst: Any, owner: Any) -> str: ...
4530
4531 class Proto(Protocol):
4532 x: int
4533
4534 class C:
4535 x = Descr()
4536
4537 class CBad:
4538 x = DescrBad()
4539
4540 a: Proto = C()
4541 b: Proto = CBad() # E: Incompatible types in assignment (expression has type "CBad", variable has type "Proto") \
4542 # N: Following member(s) of "CBad" have conflicts: \
4543 # N: x: expected "int", got "str"
4544
4545 [case testProtocolCheckDefersNode]
4546 from typing import Any, Callable, Protocol
4547
4548 class Proto(Protocol):
4549 def f(self) -> int:
4550 ...
4551
4552 def defer(f: Callable[[Any], int]) -> Callable[[Any], str]:
4553 ...
4554
4555 def bad() -> Proto:
4556 return Impl() # E: Incompatible return value type (got "Impl", expected "Proto") \
4557 # N: Following member(s) of "Impl" have conflicts: \
4558 # N: Expected: \
4559 # N: def f(self) -> int \
4560 # N: Got: \
4561 # N: def f(self) -> str \
4562
4563 class Impl:
4564 @defer
4565 def f(self) -> int: ...
4566
4567 [case testProtocolCheckDefersNode2]
4568 from typing import Any, Callable, Protocol, TypeVar
4569
4570 class Proto(Protocol):
4571 def f(self) -> int:
4572 ...
4573
4574 T = TypeVar("T")
4575 def defer(f: Callable[[T], int]) -> Callable[[T], list[int]]:
4576 ...
4577
4578 def bad() -> Proto:
4579 return Impl() # E: Incompatible return value type (got "Impl", expected "Proto") \
4580 # N: Following member(s) of "Impl" have conflicts: \
4581 # N: Expected: \
4582 # N: def f(self) -> int \
4583 # N: Got: \
4584 # N: def f(self) -> list[int] \
4585
4586 class Impl:
4587 @defer
4588 def f(self) -> int: ...
4589
4590 [case testInferCallableProtoWithAnySubclass]
4591 from typing import Any, Generic, Protocol, TypeVar
4592
4593 T = TypeVar("T", covariant=True)
4594
4595 Unknown: Any
4596 class Mock(Unknown):
4597 def __init__(self, **kwargs: Any) -> None: ...
4598 def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
4599
4600 class Factory(Protocol[T]):
4601 def __call__(self, **kwargs: Any) -> T: ...
4602
4603
4604 class Test(Generic[T]):
4605 def __init__(self, f: Factory[T]) -> None:
4606 ...
4607
4608 t = Test(Mock())
4609 reveal_type(t) # N: Revealed type is "__main__.Test[Any]"
4610 [builtins fixtures/dict.pyi]
4611
4612 [case testProtocolClassObjectDescriptor]
4613 from typing import Any, Protocol, overload
4614
4615 class Desc:
4616 @overload
4617 def __get__(self, instance: None, owner: Any) -> Desc: ...
4618 @overload
4619 def __get__(self, instance: object, owner: Any) -> int: ...
4620 def __get__(self, instance, owner):
4621 pass
4622
4623 class HasDesc(Protocol):
4624 attr: Desc
4625
4626 class HasInt(Protocol):
4627 attr: int
4628
4629 class C:
4630 attr = Desc()
4631
4632 x: HasInt = C()
4633 y: HasDesc = C
4634 z: HasInt = C # E: Incompatible types in assignment (expression has type "type[C]", variable has type "HasInt") \
4635 # N: Following member(s) of "C" have conflicts: \
4636 # N: attr: expected "int", got "Desc"
4637
4638 [case testProtocolErrorReportingNoDuplicates]
4639 from typing import Callable, Protocol, TypeVar
4640
4641 class P(Protocol):
4642 def meth(self) -> int: ...
4643
4644 class C:
4645 def meth(self) -> str: ...
4646
4647 def foo() -> None:
4648 c: P = C() # E: Incompatible types in assignment (expression has type "C", variable has type "P") \
4649 # N: Following member(s) of "C" have conflicts: \
4650 # N: Expected: \
4651 # N: def meth(self) -> int \
4652 # N: Got: \
4653 # N: def meth(self) -> str
4654 x = defer()
4655
4656 T = TypeVar("T")
4657 def deco(fn: Callable[[], T]) -> Callable[[], list[T]]: ...
4658
4659 @deco
4660 def defer() -> int: ...
4661 [builtins fixtures/list.pyi]
4662
4663 [case testProtocolClassValDescriptor]
4664 from typing import Any, Protocol, overload, ClassVar, Type
4665
4666 class Desc:
4667 @overload
4668 def __get__(self, instance: None, owner: object) -> Desc: ...
4669 @overload
4670 def __get__(self, instance: object, owner: object) -> int: ...
4671 def __get__(self, instance, owner):
4672 pass
4673
4674 class P(Protocol):
4675 x: ClassVar[Desc]
4676
4677 class C:
4678 x = Desc()
4679
4680 t: P = C()
4681 reveal_type(t.x) # N: Revealed type is "builtins.int"
4682 tt: Type[P] = C
4683 reveal_type(tt.x) # N: Revealed type is "__main__.Desc"
4684
4685 bad: P = C # E: Incompatible types in assignment (expression has type "type[C]", variable has type "P") \
4686 # N: Following member(s) of "C" have conflicts: \
4687 # N: x: expected "int", got "Desc"
4688
4689 [case testProtocolClassValCallable]
4690 from typing import Any, Protocol, overload, ClassVar, Type, Callable
4691
4692 class P(Protocol):
4693 foo: Callable[[object], int]
4694 bar: ClassVar[Callable[[object], int]]
4695
4696 class C:
4697 foo: Callable[[object], int]
4698 bar: ClassVar[Callable[[object], int]]
4699
4700 t: P = C()
4701 reveal_type(t.foo) # N: Revealed type is "def (builtins.object) -> builtins.int"
4702 reveal_type(t.bar) # N: Revealed type is "def () -> builtins.int"
4703 tt: Type[P] = C
4704 reveal_type(tt.foo) # N: Revealed type is "def (builtins.object) -> builtins.int"
4705 reveal_type(tt.bar) # N: Revealed type is "def (builtins.object) -> builtins.int"
4706
4707 [case testProtocolDecoratedSelfBound]
4708 from abc import abstractmethod
4709 from typing import Protocol, Self
4710
4711 class Proto(Protocol):
4712 @abstractmethod
4713 def foo(self, x: Self) -> None: ...
4714
4715 class Impl:
4716 def foo(self, x: Self) -> None:
4717 pass
4718
4719 x: Proto = Impl()
4720
4721 [case testIndirectDependencyOnProtocolIncremental]
4722 import a
4723 [file a.py]
4724 from b import P
4725
4726 class CNested:
4727 def f(self) -> int: ...
4728 class C:
4729 def f(self) -> CNested: ...
4730
4731 x: P = C()
4732
4733 [file b.py]
4734 from typing import Protocol
4735 from c import PNested
4736
4737 class P(Protocol):
4738 def f(self) -> PNested: ...
4739
4740 [file c.py]
4741 from typing import Protocol
4742
4743 class PNested(Protocol):
4744 def f(self) -> str: ...
4745
4746 [file c.py.2]
4747 from typing import Protocol
4748
4749 class PNested(Protocol):
4750 def f(self) -> int: ...
4751
4752 [file c.py.3]
4753 from typing import Protocol
4754
4755 class PNested(Protocol):
4756 def f(self) -> str: ...
4757 [out]
4758 tmp/a.py:8: error: Incompatible types in assignment (expression has type "C", variable has type "P")
4759 tmp/a.py:8: note: Following member(s) of "C" have conflicts:
4760 tmp/a.py:8: note: Expected:
4761 tmp/a.py:8: note: def f(self) -> PNested
4762 tmp/a.py:8: note: Got:
4763 tmp/a.py:8: note: def f(self) -> CNested
4764 [out2]
4765 [out3]
4766 tmp/a.py:8: error: Incompatible types in assignment (expression has type "C", variable has type "P")
4767 tmp/a.py:8: note: Following member(s) of "C" have conflicts:
4768 tmp/a.py:8: note: Expected:
4769 tmp/a.py:8: note: def f(self) -> PNested
4770 tmp/a.py:8: note: Got:
4771 tmp/a.py:8: note: def f(self) -> CNested
4772
4773 [case testProtocolCannotBeDisjointBase]
4774 from typing import Protocol
4775 from typing_extensions import disjoint_base
4776
4777 @disjoint_base # E: @disjoint_base cannot be used with protocol class
4778 class A(Protocol):
4779 pass
4780
4781 [builtins fixtures/tuple.pyi]
4782
4783 [case testTupleTypeSelfTypeProto]
4784 from typing import Protocol, TypeVar
4785
4786 R = TypeVar("R", covariant=True)
4787
4788 class P(Protocol[R]):
4789 def rep(self) -> R: ...
4790
4791 T = TypeVar("T")
4792 def rep(x: P[T]) -> T: ...
4793
4794 class C(tuple[int, str]):
4795 def rep(self: T) -> T: ...
4796
4797 t: C
4798 reveal_type(t) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=__main__.C]"
4799 reveal_type(rep(t)) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=__main__.C]"
4800
4801 def ok_rep(x: P[tuple[int, str]]) -> None: ...
4802 ok_rep(t)
4803
4804 def bad_rep(x: P[tuple[str, int]]) -> None: ...
4805 bad_rep(t) # E: Argument 1 to "bad_rep" has incompatible type "C"; expected "P[tuple[str, int]]" \
4806 # N: Following member(s) of "C" have conflicts: \
4807 # N: Expected: \
4808 # N: def rep(self) -> tuple[str, int] \
4809 # N: Got: \
4810 # N: def rep(self) -> C
4811 [builtins fixtures/tuple.pyi]