forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck-protocols.test
More file actions
2472 lines (1942 loc) · 60.7 KB
/
check-protocols.test
File metadata and controls
2472 lines (1942 loc) · 60.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- Simple protocol types
-- ---------------------
[case testCannotInstantiateProtocol]
from typing import Protocol
class P(Protocol):
def meth(self) -> None:
pass
P() # E: Cannot instantiate protocol class "P"
[case testSimpleProtocolOneMethod]
from typing import Protocol
class P(Protocol):
def meth(self) -> None:
pass
class B: pass
class C:
def meth(self) -> None:
pass
x: P
def fun(x: P) -> None:
x.meth()
x.meth(x) # E: Too many arguments for "meth" of "P"
x.bad # E: "P" has no attribute "bad"
x = C()
x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "P")
fun(C())
fun(B()) # E: Argument 1 to "fun" has incompatible type "B"; expected "P"
def fun2() -> P:
return C()
def fun3() -> P:
return B() # E: Incompatible return value type (got "B", expected "P")
[case testSimpleProtocolOneAbstractMethod]
from typing import Protocol
from abc import abstractmethod
class P(Protocol):
@abstractmethod
def meth(self) -> None:
pass
class B: pass
class C:
def meth(self) -> None:
pass
class D(B):
def meth(self) -> None:
pass
x: P
def fun(x: P) -> None:
x.meth()
x.meth(x) # E: Too many arguments for "meth" of "P"
x.bad # E: "P" has no attribute "bad"
x = C()
x = D()
x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "P")
fun(C())
fun(D())
fun(B()) # E: Argument 1 to "fun" has incompatible type "B"; expected "P"
fun(x)
[case testProtocolMethodBodies]
from typing import Protocol, List
class P(Protocol):
def meth(self) -> int:
return 'no way' # E: Incompatible return value type (got "str", expected "int")
# explicit ellipsis is OK in protocol methods
class P2(Protocol):
def meth2(self) -> List[int]:
...
[builtins fixtures/list.pyi]
[case testSimpleProtocolOneMethodOverride]
from typing import Protocol, Union
class P(Protocol):
def meth(self) -> Union[int, str]:
pass
class SubP(P, Protocol):
def meth(self) -> int:
pass
class B: pass
class C:
def meth(self) -> int:
pass
z: P
x: SubP
def fun(x: SubP) -> str:
x.bad # E: "SubP" has no attribute "bad"
return x.meth() # E: Incompatible return value type (got "int", expected "str")
z = x
x = C()
x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "SubP")
reveal_type(fun(C())) # E: Revealed type is 'builtins.str'
fun(B()) # E: Argument 1 to "fun" has incompatible type "B"; expected "SubP"
[case testSimpleProtocolTwoMethodsMerge]
from typing import Protocol
class P1(Protocol):
def meth1(self) -> int:
pass
class P2(Protocol):
def meth2(self) -> str:
pass
class P(P1, P2, Protocol): pass
class B: pass
class C1:
def meth1(self) -> int:
pass
class C2(C1):
def meth2(self) -> str:
pass
class C:
def meth1(self) -> int:
pass
def meth2(self) -> str:
pass
class AnotherP(Protocol):
def meth1(self) -> int:
pass
def meth2(self) -> str:
pass
x: P
reveal_type(x.meth1()) # E: Revealed type is 'builtins.int'
reveal_type(x.meth2()) # E: Revealed type is 'builtins.str'
c: C
c1: C1
c2: C2
y: AnotherP
if int():
x = c
if int():
x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "P")
if int():
x = c1 # E: Incompatible types in assignment (expression has type "C1", variable has type "P") \
# N: 'C1' is missing following 'P' protocol member: \
# N: meth2
if int():
x = c2
if int():
x = y
if int():
y = x
[case testSimpleProtocolTwoMethodsExtend]
from typing import Protocol
class P1(Protocol):
def meth1(self) -> int:
pass
class P2(P1, Protocol):
def meth2(self) -> str:
pass
class Cbad:
def meth1(self) -> int:
pass
class C:
def meth1(self) -> int:
pass
def meth2(self) -> str:
pass
x: P2
reveal_type(x.meth1()) # E: Revealed type is 'builtins.int'
reveal_type(x.meth2()) # E: Revealed type is 'builtins.str'
if int():
x = C() # OK
if int():
x = Cbad() # E: Incompatible types in assignment (expression has type "Cbad", variable has type "P2") \
# N: 'Cbad' is missing following 'P2' protocol member: \
# N: meth2
[case testProtocolMethodVsAttributeErrors]
from typing import Protocol
class P(Protocol):
def meth(self) -> int:
pass
class C:
meth: int
x: P = C() # E: Incompatible types in assignment (expression has type "C", variable has type "P") \
# N: Following member(s) of "C" have conflicts: \
# N: meth: expected "Callable[[], int]", got "int"
[case testProtocolMethodVsAttributeErrors2]
from typing import Protocol
class P(Protocol):
@property
def meth(self) -> int:
pass
class C:
def meth(self) -> int:
pass
x: P = C() # E: Incompatible types in assignment (expression has type "C", variable has type "P") \
# N: Following member(s) of "C" have conflicts: \
# N: meth: expected "int", got "Callable[[], int]"
[builtins fixtures/property.pyi]
[case testCannotAssignNormalToProtocol]
from typing import Protocol
class P(Protocol):
def meth(self) -> int:
pass
class C:
def meth(self) -> int:
pass
x: C
y: P
x = y # E: Incompatible types in assignment (expression has type "P", variable has type "C")
[case testIndependentProtocolSubtyping]
from typing import Protocol
class P1(Protocol):
def meth(self) -> int:
pass
class P2(Protocol):
def meth(self) -> int:
pass
x1: P1
x2: P2
x1 = x2
x2 = x1
def f1(x: P1) -> None: pass
def f2(x: P2) -> None: pass
f1(x2)
f2(x1)
[case testNoneDisablesProtocolImplementation]
from typing import Protocol
class MyHashable(Protocol):
def __my_hash__(self) -> int:
return 0
class C:
__my_hash__ = None
var: MyHashable = C() # E: Incompatible types in assignment (expression has type "C", variable has type "MyHashable")
[case testNoneDisablesProtocolSubclassingWithStrictOptional]
# flags: --strict-optional
from typing import Protocol
class MyHashable(Protocol):
def __my_hash__(self) -> int:
return 0
class C(MyHashable):
__my_hash__ = None # E: Incompatible types in assignment \
(expression has type "None", base class "MyHashable" defined the type as "Callable[[MyHashable], int]")
[case testProtocolsWithNoneAndStrictOptional]
# flags: --strict-optional
from typing import Protocol
class P(Protocol):
x = 0 # type: int
class C:
x = None
x: P = C() # Error!
def f(x: P) -> None: pass
f(C()) # Error!
[out]
main:9: error: Incompatible types in assignment (expression has type "C", variable has type "P")
main:9: note: Following member(s) of "C" have conflicts:
main:9: note: x: expected "int", got "None"
main:11: error: Argument 1 to "f" has incompatible type "C"; expected "P"
main:11: note: Following member(s) of "C" have conflicts:
main:11: note: x: expected "int", got "None"
-- Semanal errors in protocol types
-- --------------------------------
[case testBasicSemanalErrorsInProtocols]
from typing import Protocol, Generic, TypeVar, Iterable
T = TypeVar('T', covariant=True)
S = TypeVar('S', covariant=True)
class P1(Protocol[T, T]): # E: Duplicate type variables in Generic[...] or Protocol[...]
def meth(self) -> T:
pass
class P2(Protocol[T], Protocol[S]): # E: Only single Generic[...] or Protocol[...] can be in bases
def meth(self) -> T:
pass
class P3(Protocol[T], Generic[S]): # E: Only single Generic[...] or Protocol[...] can be in bases
def meth(self) -> T:
pass
class P4(Protocol[T]):
attr: Iterable[S] # E: Invalid type "__main__.S"
class P5(Iterable[S], Protocol[T]): # E: If Generic[...] or Protocol[...] is present it should list all type variables
def meth(self) -> T:
pass
[case testProhibitSelfDefinitionInProtocols]
from typing import Protocol
class P(Protocol):
def __init__(self, a: int) -> None:
self.a = a # E: Protocol members cannot be defined via assignment to self \
# E: "P" has no attribute "a"
class B: pass
class C:
def __init__(self, a: int) -> None:
pass
x: P
x = B()
# The above has an incompatible __init__, but mypy ignores this for nominal subtypes?
x = C(1)
class P2(Protocol):
a: int
def __init__(self) -> None:
self.a = 1
class B2(P2):
a: int
x2: P2 = B2() # OK
[case testProtocolAndRuntimeAreDefinedAlsoInTypingExtensions]
from typing_extensions import Protocol, runtime
@runtime
class P(Protocol):
def meth(self) -> int:
pass
x: object
if isinstance(x, P):
reveal_type(x) # E: Revealed type is '__main__.P'
reveal_type(x.meth()) # E: Revealed type is 'builtins.int'
class C:
def meth(self) -> int:
pass
z: P = C()
[builtins fixtures/dict.pyi]
[case testProtocolsCannotInheritFromNormal]
from typing import Protocol
class C: pass
class D: pass
class P(C, Protocol): # E: All bases of a protocol must be protocols
attr: int
class P2(P, D, Protocol): # E: All bases of a protocol must be protocols
pass
P2() # E: Cannot instantiate abstract class 'P2' with abstract attribute 'attr'
p: P2
reveal_type(p.attr) # E: Revealed type is 'builtins.int'
-- Generic protocol types
-- ----------------------
[case testGenericMethodWithProtocol]
from typing import Protocol, TypeVar
T = TypeVar('T')
class P(Protocol):
def meth(self, x: int) -> int:
return x
class C:
def meth(self, x: T) -> T:
return x
x: P = C()
[case testGenericMethodWithProtocol2]
from typing import Protocol, TypeVar
T = TypeVar('T')
class P(Protocol):
def meth(self, x: T) -> T:
return x
class C:
def meth(self, x: int) -> int:
return x
x: P = C()
[out]
main:11: error: Incompatible types in assignment (expression has type "C", variable has type "P")
main:11: note: Following member(s) of "C" have conflicts:
main:11: note: Expected:
main:11: note: def [T] meth(self, x: T) -> T
main:11: note: Got:
main:11: note: def meth(self, x: int) -> int
[case testAutomaticProtocolVariance]
from typing import TypeVar, Protocol
T = TypeVar('T')
# In case of these errors we proceed with declared variance.
class Pco(Protocol[T]): # E: Invariant type variable 'T' used in protocol where covariant one is expected
def meth(self) -> T:
pass
class Pcontra(Protocol[T]): # E: Invariant type variable 'T' used in protocol where contravariant one is expected
def meth(self, x: T) -> None:
pass
class Pinv(Protocol[T]):
attr: T
class A: pass
class B(A): pass
x1: Pco[B]
y1: Pco[A]
if int():
x1 = y1 # E: Incompatible types in assignment (expression has type "Pco[A]", variable has type "Pco[B]")
if int():
y1 = x1 # E: Incompatible types in assignment (expression has type "Pco[B]", variable has type "Pco[A]")
x2: Pcontra[B]
y2: Pcontra[A]
if int():
y2 = x2 # E: Incompatible types in assignment (expression has type "Pcontra[B]", variable has type "Pcontra[A]")
if int():
x2 = y2 # E: Incompatible types in assignment (expression has type "Pcontra[A]", variable has type "Pcontra[B]")
x3: Pinv[B]
y3: Pinv[A]
if int():
y3 = x3 # E: Incompatible types in assignment (expression has type "Pinv[B]", variable has type "Pinv[A]")
if int():
x3 = y3 # E: Incompatible types in assignment (expression has type "Pinv[A]", variable has type "Pinv[B]")
[case testProtocolVarianceWithCallableAndList]
from typing import Protocol, TypeVar, Callable, List
T = TypeVar('T')
S = TypeVar('S')
T_co = TypeVar('T_co', covariant=True)
class P(Protocol[T, S]): # E: Invariant type variable 'T' used in protocol where covariant one is expected \
# E: Invariant type variable 'S' used in protocol where contravariant one is expected
def fun(self, callback: Callable[[T], S]) -> None: pass
class P2(Protocol[T_co]): # E: Covariant type variable 'T_co' used in protocol where invariant one is expected
lst: List[T_co]
[builtins fixtures/list.pyi]
[case testProtocolVarianceWithUnusedVariable]
from typing import Protocol, TypeVar
T = TypeVar('T')
class P(Protocol[T]): # E: Invariant type variable 'T' used in protocol where covariant one is expected
attr: int
[case testGenericProtocolsInference1]
from typing import Protocol, Sequence, TypeVar
T = TypeVar('T', covariant=True)
class Closeable(Protocol[T]):
def close(self) -> T:
pass
class F:
def close(self) -> int:
return 0
def close(arg: Closeable[T]) -> T:
return arg.close()
def close_all(args: Sequence[Closeable[T]]) -> T:
for arg in args:
arg.close()
return args[0].close()
arg: Closeable[int]
reveal_type(close(F())) # E: Revealed type is 'builtins.int*'
reveal_type(close(arg)) # E: Revealed type is 'builtins.int*'
reveal_type(close_all([F()])) # E: Revealed type is 'builtins.int*'
reveal_type(close_all([arg])) # E: Revealed type is 'builtins.int*'
[builtins fixtures/isinstancelist.pyi]
[typing fixtures/typing-full.pyi]
[case testProtocolGenericInference2]
from typing import Generic, TypeVar, Protocol
T = TypeVar('T')
S = TypeVar('S')
class P(Protocol[T, S]):
x: T
y: S
class C:
x: int
y: int
def fun3(x: P[T, T]) -> T:
pass
reveal_type(fun3(C())) # E: Revealed type is 'builtins.int*'
[case testProtocolGenericInferenceCovariant]
from typing import Generic, TypeVar, Protocol
T = TypeVar('T', covariant=True)
S = TypeVar('S', covariant=True)
U = TypeVar('U')
class P(Protocol[T, S]):
def x(self) -> T: pass
def y(self) -> S: pass
class C:
def x(self) -> int: pass
def y(self) -> int: pass
def fun4(x: U, y: P[U, U]) -> U:
pass
reveal_type(fun4('a', C())) # E: Revealed type is 'builtins.object*'
[case testUnrealtedGenericProtolsEquivalent]
from typing import TypeVar, Protocol
T = TypeVar('T')
class PA(Protocol[T]):
attr: int
def meth(self) -> T: pass
def other(self, arg: T) -> None: pass
class PB(Protocol[T]): # exactly the same as above
attr: int
def meth(self) -> T: pass
def other(self, arg: T) -> None: pass
def fun(x: PA[T]) -> PA[T]:
y: PB[T] = x
z: PB[T]
return z
x: PA
y: PB
x = y
y = x
xi: PA[int]
yi: PB[int]
xi = yi
yi = xi
[case testGenericSubProtocols]
from typing import TypeVar, Protocol, Tuple, Generic
T = TypeVar('T')
S = TypeVar('S')
class P1(Protocol[T]):
attr1: T
class P2(P1[T], Protocol[T, S]):
attr2: Tuple[T, S]
class C:
def __init__(self, a1: int, a2: Tuple[int, int]) -> None:
self.attr1 = a1
self.attr2 = a2
c: C
var: P2[int, int] = c
var2: P2[int, str] = c # E: Incompatible types in assignment (expression has type "C", variable has type "P2[int, str]") \
# N: Following member(s) of "C" have conflicts: \
# N: attr2: expected "Tuple[int, str]", got "Tuple[int, int]"
class D(Generic[T]):
attr1: T
class E(D[T]):
attr2: Tuple[T, T]
def f(x: T) -> T:
z: P2[T, T] = E[T]()
y: P2[T, T] = D[T]() # E: Incompatible types in assignment (expression has type "D[T]", variable has type "P2[T, T]") \
# N: 'D' is missing following 'P2' protocol member: \
# N: attr2
return x
[builtins fixtures/isinstancelist.pyi]
[case testGenericSubProtocolsExtensionInvariant]
from typing import TypeVar, Protocol, Union
T = TypeVar('T')
S = TypeVar('S')
class P1(Protocol[T]):
attr1: T
class P2(Protocol[T]):
attr2: T
class P(P1[T], P2[S], Protocol):
pass
class C:
attr1: int
attr2: str
class A:
attr1: A
class B:
attr2: B
class D(A, B): pass
x: P = D() # Same as P[Any, Any]
var: P[Union[int, P], Union[P, str]] = C() # E: Incompatible types in assignment (expression has type "C", variable has type "P[Union[int, P[Any, Any]], Union[P[Any, Any], str]]") \
# N: Following member(s) of "C" have conflicts: \
# N: attr1: expected "Union[int, P[Any, Any]]", got "int" \
# N: attr2: expected "Union[P[Any, Any], str]", got "str"
[case testGenericSubProtocolsExtensionCovariant]
from typing import TypeVar, Protocol, Union
T = TypeVar('T', covariant=True)
S = TypeVar('S', covariant=True)
class P1(Protocol[T]):
def attr1(self) -> T: pass
class P2(Protocol[T]):
def attr2(self) -> T: pass
class P(P1[T], P2[S], Protocol):
pass
class C:
def attr1(self) -> int: pass
def attr2(self) -> str: pass
var: P[Union[int, P], Union[P, str]] = C() # OK for covariant
var2: P[Union[str, P], Union[P, int]] = C()
[out]
main:18: error: Incompatible types in assignment (expression has type "C", variable has type "P[Union[str, P[Any, Any]], Union[P[Any, Any], int]]")
main:18: note: Following member(s) of "C" have conflicts:
main:18: note: Expected:
main:18: note: def attr1(self) -> Union[str, P[Any, Any]]
main:18: note: Got:
main:18: note: def attr1(self) -> int
main:18: note: Expected:
main:18: note: def attr2(self) -> Union[P[Any, Any], int]
main:18: note: Got:
main:18: note: def attr2(self) -> str
[case testSelfTypesWithProtocolsBehaveAsWithNominal]
from typing import Protocol, TypeVar
T = TypeVar('T', bound=Shape)
class Shape(Protocol):
def combine(self: T, other: T) -> T:
pass
class NonProtoShape:
def combine(self: T, other: T) -> T:
pass
class Circle:
def combine(self: T, other: Shape) -> T:
pass
class Triangle:
def combine(self, other: Shape) -> Shape:
pass
class Bad:
def combine(self, other: int) -> str:
pass
def f(s: Shape) -> None: pass
f(NonProtoShape())
f(Circle())
s: Shape
if int():
s = Triangle()
s = Bad()
n2: NonProtoShape = s
[out]
main:26: error: Incompatible types in assignment (expression has type "Triangle", variable has type "Shape")
main:26: note: Following member(s) of "Triangle" have conflicts:
main:26: note: Expected:
main:26: note: def combine(self, other: Triangle) -> Triangle
main:26: note: Got:
main:26: note: def combine(self, other: Shape) -> Shape
main:27: error: Incompatible types in assignment (expression has type "Bad", variable has type "Shape")
main:27: note: Following member(s) of "Bad" have conflicts:
main:27: note: Expected:
main:27: note: def combine(self, other: Bad) -> Bad
main:27: note: Got:
main:27: note: def combine(self, other: int) -> str
main:29: error: Incompatible types in assignment (expression has type "Shape", variable has type "NonProtoShape")
[case testBadVarianceInProtocols]
from typing import Protocol, TypeVar
T_co = TypeVar('T_co', covariant=True)
T_contra = TypeVar('T_contra', contravariant=True)
class Proto(Protocol[T_co, T_contra]): # type: ignore
def one(self, x: T_co) -> None: # E: Cannot use a covariant type variable as a parameter
pass
def other(self) -> T_contra: # E: Cannot use a contravariant type variable as return type
pass
# Check that we respect user overrides of variance after the errors are reported
x: Proto[int, float]
y: Proto[float, int]
y = x # OK
[builtins fixtures/list.pyi]
[case testSubtleBadVarianceInProtocols]
from typing import Protocol, TypeVar, Iterable, Sequence
T_co = TypeVar('T_co', covariant=True)
T_contra = TypeVar('T_contra', contravariant=True)
class Proto(Protocol[T_co, T_contra]): # E: Covariant type variable 'T_co' used in protocol where contravariant one is expected \
# E: Contravariant type variable 'T_contra' used in protocol where covariant one is expected
def one(self, x: Iterable[T_co]) -> None:
pass
def other(self) -> Sequence[T_contra]:
pass
# Check that we respect user overrides of variance after the errors are reported
x: Proto[int, float]
y: Proto[float, int]
y = x # OK
[builtins fixtures/list.pyi]
-- Recursive protocol types
-- ------------------------
[case testRecursiveProtocols1]
from typing import Protocol, Sequence, List, Generic, TypeVar
T = TypeVar('T')
class Traversable(Protocol):
@property
def leaves(self) -> Sequence[Traversable]: pass
class C: pass
class D(Generic[T]):
leaves: List[D[T]]
t: Traversable
t = D[int]() # OK
if int():
t = C() # E: Incompatible types in assignment (expression has type "C", variable has type "Traversable")
[builtins fixtures/list.pyi]
[typing fixtures/typing-full.pyi]
[case testRecursiveProtocols2]
from typing import Protocol, TypeVar
T = TypeVar('T')
class Linked(Protocol[T]):
val: T
def next(self) -> Linked[T]: pass
class L:
val: int
def next(self) -> L: pass
def last(seq: Linked[T]) -> T:
pass
reveal_type(last(L())) # E: Revealed type is 'builtins.int*'
[builtins fixtures/list.pyi]
[case testRecursiveProtocolSubtleMismatch]
from typing import Protocol, TypeVar
T = TypeVar('T')
class Linked(Protocol[T]):
val: T
def next(self) -> Linked[T]: pass
class L:
val: int
def next(self) -> int: pass
def last(seq: Linked[T]) -> T:
pass
last(L()) # E: Argument 1 to "last" has incompatible type "L"; expected "Linked[<nothing>]"
[case testMutuallyRecursiveProtocols]
from typing import Protocol, Sequence, List
class P1(Protocol):
@property
def attr1(self) -> Sequence[P2]: pass
class P2(Protocol):
@property
def attr2(self) -> Sequence[P1]: pass
class C: pass
class A:
attr1: List[B]
class B:
attr2: List[A]
t: P1
t = A() # OK
if int():
t = B() # E: Incompatible types in assignment (expression has type "B", variable has type "P1")
t = C() # E: Incompatible types in assignment (expression has type "C", variable has type "P1")
[builtins fixtures/list.pyi]
[typing fixtures/typing-full.pyi]
[case testMutuallyRecursiveProtocolsTypesWithSubteMismatch]
from typing import Protocol, Sequence, List
class P1(Protocol):
@property
def attr1(self) -> Sequence[P2]: pass
class P2(Protocol):
@property
def attr2(self) -> Sequence[P1]: pass
class C: pass
class A:
attr1: List[B]
class B:
attr2: List[C]
t: P1
t = A() # E: Incompatible types in assignment (expression has type "A", variable has type "P1") \
# N: Following member(s) of "A" have conflicts: \
# N: attr1: expected "Sequence[P2]", got "List[B]"
[builtins fixtures/list.pyi]
[case testMutuallyRecursiveProtocolsTypesWithSubteMismatchWriteable]
from typing import Protocol
class P1(Protocol):
@property
def attr1(self) -> P2: pass
class P2(Protocol):
attr2: P1
class A:
attr1: B
class B:
attr2: A
x: P1 = A() # E: Incompatible types in assignment (expression has type "A", variable has type "P1") \
# N: Following member(s) of "A" have conflicts: \
# N: attr1: expected "P2", got "B"
[builtins fixtures/property.pyi]
-- FIXME: things like this should work
[case testWeirdRecursiveInferenceForProtocols-skip]
from typing import Protocol, TypeVar, Generic
T_co = TypeVar('T_co', covariant=True)
T = TypeVar('T')
class P(Protocol[T_co]):
def meth(self) -> P[T_co]: pass
class C(Generic[T]):
def meth(self) -> C[T]: pass
x: C[int]
def f(arg: P[T]) -> T: pass
reveal_type(f(x)) #E: Revealed type is 'builtins.int*'
-- @property, @classmethod and @staticmethod in protocol types
-- -----------------------------------------------------------
[case testCannotInstantiateAbstractMethodExplicitProtocolSubtypes]
from typing import Protocol
from abc import abstractmethod
class P(Protocol):
@abstractmethod
def meth(self) -> int:
pass
class A(P):
pass
A() # E: Cannot instantiate abstract class 'A' with abstract attribute 'meth'
class C(A):
def meth(self) -> int:
pass
class C2(P):
def meth(self) -> int:
pass
C()
C2()
[case testCannotInstantiateAbstractVariableExplicitProtocolSubtypes]
from typing import Protocol
class P(Protocol):
attr: int
class A(P):
pass
A() # E: Cannot instantiate abstract class 'A' with abstract attribute 'attr'
class C(A):
attr: int
class C2(P):
def __init__(self) -> None:
self.attr = 1
C()
C2()
class P2(Protocol):
attr: int = 1
class B(P2): pass
B() # OK, attr is not abstract
[case testClassVarsInProtocols]
from typing import Protocol, ClassVar
class PInst(Protocol):
v: int
class PClass(Protocol):
v: ClassVar[int]
class CInst:
v: int
class CClass:
v: ClassVar[int]
x: PInst
y: PClass
x = CInst()
if int():
x = CClass() # E: Incompatible types in assignment (expression has type "CClass", variable has type "PInst") \
# N: Protocol member PInst.v expected instance variable, got class variable
y = CClass()
if int():
y = CInst() # E: Incompatible types in assignment (expression has type "CInst", variable has type "PClass") \
# N: Protocol member PClass.v expected class variable, got instance variable
[case testPropertyInProtocols]
from typing import Protocol
class PP(Protocol):
@property
def attr(self) -> int:
pass
class P(Protocol):
attr: int
x: P
y: PP
y = x
x2: P
y2: PP
x2 = y2 # E: Incompatible types in assignment (expression has type "PP", variable has type "P") \
# N: Protocol member P.attr expected settable variable, got read-only attribute