forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check-generics.test
3446 lines (2710 loc) · 96.6 KB
/
check-generics.test
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 generic types
-- --------------------
[case testGenericMethodReturnType]
from typing import TypeVar, Generic
T = TypeVar('T')
a: A[B]
b: B
c: C
if int():
c = a.f() # E: Incompatible types in assignment (expression has type "B", variable has type "C")
b = a.f()
class A(Generic[T]):
def f(self) -> T: pass
class B: pass
class C: pass
[builtins fixtures/tuple.pyi]
[case testGenericMethodArgument]
from typing import TypeVar, Generic
T = TypeVar('T')
class A(Generic[T]):
def f(self, a: T) -> None: pass
a: A[B]
b: B
c: C
a.f(c) # E: Argument 1 to "f" of "A" has incompatible type "C"; expected "B"
a.f(b)
class B: pass
class C: pass
[case testGenericMemberVariable]
from typing import TypeVar, Generic
T = TypeVar('T')
class A(Generic[T]):
def __init__(self, v: T) -> None:
self.v = v
a: A[B]
b: B
c: C
a.v = c # Fail
a.v = b
class B: pass
class C: pass
[builtins fixtures/tuple.pyi]
[out]
main:10: error: Incompatible types in assignment (expression has type "C", variable has type "B")
[case testGenericMemberVariable2]
from typing import TypeVar, Generic
T = TypeVar('T')
a: A[B]
b: B
c: C
a.v = c # Fail
a.v = b
class A(Generic[T]):
v: T
class B: pass
class C: pass
[builtins fixtures/tuple.pyi]
[out]
main:6: error: Incompatible types in assignment (expression has type "C", variable has type "B")
[case testSimpleGenericSubtyping]
from typing import TypeVar, Generic
T = TypeVar('T')
b: A[B]
bb: A[B]
c: A[C]
if int():
c = b # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[C]")
b = c # E: Incompatible types in assignment (expression has type "A[C]", variable has type "A[B]")
if int():
b = b
if int():
b = bb
class A(Generic[T]): pass
class B: pass
class C(B): pass
[builtins fixtures/tuple.pyi]
[case testGenericTypeCompatibilityWithAny]
from typing import Any, TypeVar, Generic
T = TypeVar('T')
b: A[B]
c: A[C]
d: A[Any]
b = d
c = d
d = b
d = c
class A(Generic[T]): pass
class B: pass
class C(B): pass
[builtins fixtures/tuple.pyi]
[out]
[case testTypeVariableAsTypeArgument]
from typing import TypeVar, Generic
T = TypeVar('T')
a: A[B]
b: A[B]
c: A[C]
a.v = c # E: Incompatible types in assignment (expression has type "A[C]", variable has type "A[B]")
if int():
c = a.v # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[C]")
a.v = b
if int():
b = a.v
class A(Generic[T]):
v = None # type: A[T]
class B: pass
class C: pass
[case testMultipleGenericTypeParametersWithMemberVars]
from typing import TypeVar, Generic
S = TypeVar('S')
T = TypeVar('T')
a: A[B, C]
s: B
t: C
if int():
t = a.s # E: Incompatible types in assignment (expression has type "B", variable has type "C")
s = a.t # E: Incompatible types in assignment (expression has type "C", variable has type "B")
if int():
s = a.s
t = a.t
class A(Generic[S, T]):
s: S
t: T
class B: pass
class C: pass
[case testMultipleGenericTypeParametersWithMethods]
from typing import TypeVar, Generic
S = TypeVar('S')
T = TypeVar('T')
a: A[B, C]
s: B
t: C
a.f(s, s) # Fail
a.f(t, t) # Fail
a.f(s, t)
class A(Generic[S, T]):
def f(self, s: S, t: T) -> None: pass
class B: pass
class C: pass
[out]
main:8: error: Argument 2 to "f" of "A" has incompatible type "B"; expected "C"
main:9: error: Argument 1 to "f" of "A" has incompatible type "C"; expected "B"
[case testMultipleGenericTypeParametersAndSubtyping]
from typing import TypeVar, Generic
S = TypeVar('S')
T = TypeVar('T')
bc: A[B, C]
bb: A[B, B]
cb: A[C, B]
if int():
bb = bc # E: Incompatible types in assignment (expression has type "A[B, C]", variable has type "A[B, B]")
if int():
bb = cb # E: Incompatible types in assignment (expression has type "A[C, B]", variable has type "A[B, B]")
bc = bb # E: Incompatible types in assignment (expression has type "A[B, B]", variable has type "A[B, C]")
if int():
bb = bb
bc = bc
class A(Generic[S, T]):
s: S
t: T
class B: pass
class C(B):pass
-- Simple generic type bodies
-- --------------------------
[case testGenericTypeBody1]
from typing import TypeVar, Generic
T = TypeVar('T')
class A(Generic[T]):
a: T
def f(self, b: T) -> T:
self.f(x) # Fail
d = self # type: A[B] # Fail
self.a = self.f(self.a)
return self.a
c = self # type: A[T]
x: B
class B: pass
[out]
main:7: error: Argument 1 to "f" of "A" has incompatible type "B"; expected "T"
main:8: error: Incompatible types in assignment (expression has type "A[T]", variable has type "A[B]")
[case testGenericTypeBodyWithMultipleVariables]
from typing import TypeVar, Generic
S = TypeVar('S')
T = TypeVar('T')
class A(Generic[S, T]):
def f(self) -> None:
s: S
t: T
if int():
s = t # E: Incompatible types in assignment (expression has type "T", variable has type "S")
t = s # E: Incompatible types in assignment (expression has type "S", variable has type "T")
a = self # type: A[S, B] # E: Incompatible types in assignment (expression has type "A[S, T]", variable has type "A[S, B]")
b = self # type: A[T, T] # E: Incompatible types in assignment (expression has type "A[S, T]", variable has type "A[T, T]")
c = self # type: A[S, T]
if int():
t = t
class B: pass
[out]
[case testCompatibilityOfNoneWithTypeVar]
# flags: --no-strict-optional
from typing import TypeVar, Generic
T = TypeVar('T')
class A(Generic[T]):
def f(self) -> None:
a = None # type: T
a = None
[out]
[case testCompatibilityOfTypeVarWithObject]
# flags: --no-strict-optional
from typing import TypeVar, Generic
T = TypeVar('T')
class A(Generic[T]):
def f(self) -> T:
a = object() # type: T # E: Incompatible types in assignment (expression has type "object", variable has type "T")
if int():
a = object() # E: Incompatible types in assignment (expression has type "object", variable has type "T")
b = self.f() # type: object
if int():
b = self.f()
return None
[out]
-- Operations with generic types
-- -----------------------------
[case testGenericOperations]
from typing import TypeVar, Generic
S = TypeVar('S')
T = TypeVar('T')
a: A[B, C]
b: B
c: C
if int():
b = a + b # E: Incompatible types in assignment (expression has type "C", variable has type "B")
c = a + c # E: Unsupported operand types for + ("A[B, C]" and "C")
if int():
c = a[c] # E: Incompatible types in assignment (expression has type "B", variable has type "C")
b = a[b] # E: Invalid index type "B" for "A[B, C]"; expected type "C"
if int():
c = a + b
b = a[c]
class A(Generic[S, T]):
def __add__(self, a: S) -> T: pass
def __getitem__(self, i: T) -> S: pass
class B: pass
class C: pass
[case testOperatorAssignmentWithIndexLvalue1]
from typing import TypeVar, Generic
T = TypeVar('T')
b: B
c: C
ac: A[C]
ac[b] += b # Fail
ac[c] += c # Fail
ac[b] += c
ac[b] = ac[b] + c
class A(Generic[T]):
def __getitem__(self, i: 'B') -> T: pass
def __setitem__(self, i: 'B', v: T) -> None: pass
class B: pass
class C:
def __add__(self, o: 'C') -> 'C': pass
[out]
main:7: error: Unsupported operand types for + ("C" and "B")
main:8: error: Invalid index type "C" for "A[C]"; expected type "B"
[case testOperatorAssignmentWithIndexLvalue2]
from typing import TypeVar, Generic
T = TypeVar('T')
b: B
c: C
ac: A[C]
ac[b] += c # Fail
ac[c] += c # Fail
ac[b] = ac[b] + c # Fail
class A(Generic[T]):
def __getitem__(self, i: 'B') -> T: pass
def __setitem__(self, i: 'C', v: T) -> None: pass
class B: pass
class C:
def __add__(self, o: 'C') -> 'C': pass
[out]
main:7: error: Invalid index type "B" for "A[C]"; expected type "C"
main:8: error: Invalid index type "C" for "A[C]"; expected type "B"
main:9: error: Invalid index type "B" for "A[C]"; expected type "C"
-- Nested generic types
-- --------------------
[case testNestedGenericTypes]
from typing import TypeVar, Generic
T = TypeVar('T')
aab: A[A[B]]
aac: A[A[C]]
ab: A[B]
ac: A[C]
if int():
ac = aab.x # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[C]")
ac.y = aab # E: Incompatible types in assignment (expression has type "A[A[B]]", variable has type "A[A[C]]")
if int():
ab = aab.x
ac = aac.x
ab.y = aab
ac.y = aac
class A(Generic[T]):
x: T
y: A[A[T]]
class B:
pass
class C:
pass
-- Generic functions
-- -----------------
[case testTypeCheckingGenericFunctionBody]
from typing import TypeVar, Generic
S = TypeVar('S')
T = TypeVar('T')
class A: pass
class p(Generic[T, S]):
def __init__(self, t: T, a: S) -> None: pass
def f(s: S, t: T) -> p[T, A]:
a = t # type: S # E: Incompatible types in assignment (expression has type "T", variable has type "S")
if int():
s = t # E: Incompatible types in assignment (expression has type "T", variable has type "S")
p_s_a: p[S, A]
if s:
return p_s_a # E: Incompatible return value type (got "p[S, A]", expected "p[T, A]")
b = t # type: T
c = s # type: S
p_t_a: p[T, A]
return p_t_a
[out]
[case testTypeCheckingGenericMethodBody]
from typing import TypeVar, Generic
T = TypeVar('T')
S = TypeVar('S')
class p(Generic[T, S]):
def __init__(self, t: T, a: S) -> None: pass
class A(Generic[T]):
def f(self, s: S, t: T) -> p[S, T]:
if int():
s = t # E: Incompatible types in assignment (expression has type "T", variable has type "S")
p_s_s: p[S, S]
if s:
return p_s_s # E: Incompatible return value type (got "p[S, S]", expected "p[S, T]")
p_t_t: p[T, T]
if t:
return p_t_t # E: Incompatible return value type (got "p[T, T]", expected "p[S, T]")
if 1:
t = t
s = s
p_s_t: p[S, T]
return p_s_t
[out]
[case testProhibitTypeApplicationToGenericFunctions]
from typing import TypeVar
T = TypeVar('T')
def f(x: T) -> T: pass
y = f[int] # E: Type application is only supported for generic classes
[out]
-- Generic types in expressions
-- ----------------------------
[case testTypeApplicationArgs]
from typing import TypeVar, Generic
T = TypeVar('T')
class Node(Generic[T]):
def __init__(self, x: T) -> None:
...
Node[int]() # E: Missing positional argument "x" in call to "Node"
Node[int](1, 1, 1) # E: Too many arguments for "Node"
[out]
[case testTypeApplicationTvars]
from typing import TypeVar, Generic
T = TypeVar('T')
S = TypeVar('S')
class A(Generic[T, S]): pass
A[int]() # E: Type application has too few types (2 expected)
A[int, str, int]() # E: Type application has too many types (2 expected)
[out]
[case testInvalidTypeApplicationType]
a: A
class A: pass
a[A]() # E: Value of type "A" is not indexable
A[A]() # E: The type "Type[A]" is not generic and not indexable
[out]
[case testTypeApplicationArgTypes]
from typing import TypeVar, Generic
T = TypeVar('T')
class Node(Generic[T]):
def __init__(self, x: T) -> None:
...
Node[int](1)
Node[int]('a') # E: Argument 1 to "Node" has incompatible type "str"; expected "int"
class Dummy(Generic[T]):
def meth(self, x: T) -> None:
...
def methout(self) -> T:
...
Dummy[int]().meth(1)
Dummy[int]().meth('a') # E: Argument 1 to "meth" of "Dummy" has incompatible type "str"; expected "int"
reveal_type(Dummy[int]()) # N: Revealed type is "__main__.Dummy[builtins.int]"
reveal_type(Dummy[int]().methout()) # N: Revealed type is "builtins.int"
[out]
[case testTypeApplicationArgTypesSubclasses]
from typing import TypeVar, Generic
T = TypeVar('T')
S = TypeVar('S')
class C(Generic[T, S]):
def __init__(self, x: T, y: S) -> None:
...
class D(C[int, T]): ...
D[str](1, 'a')
D[str](1, 1) # E: Argument 2 to "D" has incompatible type "int"; expected "str"
class E(D[str]): ...
E(1, 'a')
E(1, 1) # E: Argument 2 to "E" has incompatible type "int"; expected "str"
[out]
[case testTypeApplicationAlias]
from typing import TypeVar, Generic
T = TypeVar('T')
class Node(Generic[T]):
def __init__(self, x: T) -> None:
...
Alias = Node
Alias[int](1)
Alias[int]("a") # E: Argument 1 to "Node" has incompatible type "str"; expected "int"
[out]
[case testTypeApplicationCrash]
type[int] # this was crashing, see #2302 (comment) # E: The type "Type[type]" is not generic and not indexable
[out]
-- Generic type aliases
-- --------------------
[case testGenericTypeAliasesBasic]
from typing import TypeVar, Generic
T = TypeVar('T')
S = TypeVar('S')
class Node(Generic[T, S]):
def __init__(self, x: T, y: S) -> None:
...
IntNode = Node[int, S]
IntIntNode = Node[int, int]
SameNode = Node[T, T]
n = Node(1, 1) # type: IntIntNode
n1 = Node(1, 'a') # type: IntIntNode # E: Argument 2 to "Node" has incompatible type "str"; expected "int"
m = Node(1, 1) # type: IntNode
m1 = Node('x', 1) # type: IntNode # E: Argument 1 to "Node" has incompatible type "str"; expected "int"
m2 = Node(1, 1) # type: IntNode[str] # E: Argument 2 to "Node" has incompatible type "int"; expected "str"
s = Node(1, 1) # type: SameNode[int]
reveal_type(s) # N: Revealed type is "__main__.Node[builtins.int, builtins.int]"
s1 = Node(1, 'x') # type: SameNode[int] # E: Argument 2 to "Node" has incompatible type "str"; expected "int"
[out]
[case testGenericTypeAliasesBasic2]
from typing import TypeVar, Generic
T = TypeVar('T')
S = TypeVar('S')
class Node(Generic[T, S]):
def __init__(self, x: T, y: S) -> None:
...
IntNode = Node[int, S]
IntIntNode = Node[int, int]
SameNode = Node[T, T]
def output_bad() -> IntNode[str]:
return Node(1, 1) # Error - bad return type, see out
def input(x: IntNode[str]) -> None:
pass
input(Node(1, 's'))
input(Node(1, 1)) # E: Argument 2 to "Node" has incompatible type "int"; expected "str"
def output() -> IntNode[str]:
return Node(1, 'x')
reveal_type(output()) # N: Revealed type is "__main__.Node[builtins.int, builtins.str]"
def func(x: IntNode[T]) -> IntNode[T]:
return x
reveal_type(func) # N: Revealed type is "def [T] (x: __main__.Node[builtins.int, T`-1]) -> __main__.Node[builtins.int, T`-1]"
func(1) # E: Argument 1 to "func" has incompatible type "int"; expected "Node[int, Never]"
func(Node('x', 1)) # E: Argument 1 to "Node" has incompatible type "str"; expected "int"
reveal_type(func(Node(1, 'x'))) # N: Revealed type is "__main__.Node[builtins.int, builtins.str]"
def func2(x: SameNode[T]) -> SameNode[T]:
return x
reveal_type(func2) # N: Revealed type is "def [T] (x: __main__.Node[T`-1, T`-1]) -> __main__.Node[T`-1, T`-1]"
func2(Node(1, 'x')) # E: Cannot infer type argument 1 of "func2"
y = func2(Node('x', 'x'))
reveal_type(y) # N: Revealed type is "__main__.Node[builtins.str, builtins.str]"
def wrap(x: T) -> IntNode[T]:
return Node(1, x)
z: str
reveal_type(wrap(z)) # N: Revealed type is "__main__.Node[builtins.int, builtins.str]"
[out]
main:13: error: Argument 2 to "Node" has incompatible type "int"; expected "str"
-- Error formatting is a bit different (and probably better) with new analyzer
[case testGenericTypeAliasesWrongAliases]
# flags: --show-column-numbers --no-strict-optional
from typing import TypeVar, Generic, List, Callable, Tuple, Union
T = TypeVar('T')
S = TypeVar('S')
class Node(Generic[T, S]):
def __init__(self, x: T, y: S) -> None:
...
A = Node[T] # Error
B = Node[T, T]
C = Node[T, T, T] # Error
D = Node[T, S]
E = Node[Node[T, T], List[T]]
F = Node[List[T, T], S] # Error
G = Callable[..., List[T, T]] # Error
H = Union[int, Tuple[T, Node[T]]] # Error
h: H # This was reported on previous line
h1: H[int, str] # Error
x = None # type: D[int, str]
reveal_type(x)
y = None # type: E[int]
reveal_type(y)
X = T # Error
[builtins fixtures/list.pyi]
[out]
main:9:5: error: "Node" expects 2 type arguments, but 1 given
main:11:5: error: "Node" expects 2 type arguments, but 3 given
main:15:10: error: "list" expects 1 type argument, but 2 given
main:16:19: error: "list" expects 1 type argument, but 2 given
main:17:25: error: "Node" expects 2 type arguments, but 1 given
main:19:5: error: Bad number of arguments for type alias, expected: 1, given: 2
main:22:13: note: Revealed type is "__main__.Node[builtins.int, builtins.str]"
main:24:13: note: Revealed type is "__main__.Node[__main__.Node[builtins.int, builtins.int], builtins.list[builtins.int]]"
main:26:5: error: Type variable "__main__.T" is invalid as target for type alias
[case testGenericTypeAliasesForAliases]
from typing import TypeVar, Generic, List, Union
T = TypeVar('T')
S = TypeVar('S')
class Node(Generic[T, S]):
def __init__(self, x: T, y: S) -> None:
pass
ListedNode = Node[List[T], List[S]]
Second = ListedNode[int, T]
Third = Union[int, Second[str]]
def f2(x: T) -> Second[T]:
return Node([1], [x])
reveal_type(f2('a')) # N: Revealed type is "__main__.Node[builtins.list[builtins.int], builtins.list[builtins.str]]"
def f3() -> Third:
return Node([1], ['x'])
reveal_type(f3()) # N: Revealed type is "Union[builtins.int, __main__.Node[builtins.list[builtins.int], builtins.list[builtins.str]]]"
[builtins fixtures/list.pyi]
[case testGenericTypeAliasesWithNestedArgs]
# flags: --pretty --show-error-codes
import other
a: other.Array[float]
reveal_type(a) # N: Revealed type is "other.array[Any, other.dtype[builtins.float]]"
[out]
main:3: error: Type argument "float" of "Array" must be a subtype of "generic" [type-var]
a: other.Array[float]
^
[file other.py]
from typing import Any, Generic, TypeVar
DT = TypeVar("DT", covariant=True, bound='dtype[Any]')
DTS = TypeVar("DTS", covariant=True, bound='generic')
S = TypeVar("S", bound=Any)
ST = TypeVar("ST", bound='generic', covariant=True)
class common: pass
class generic(common): pass
class dtype(Generic[DTS]): pass
class array(common, Generic[S, DT]): pass
Array = array[Any, dtype[ST]]
[case testGenericTypeAliasesAny]
from typing import TypeVar, Generic
T = TypeVar('T')
S = TypeVar('S')
class Node(Generic[T, S]):
def __init__(self, x: T, y: S) -> None:
self.x = x
self.y = y
IntNode = Node[int, S]
AnyNode = Node[S, T]
def output() -> IntNode[str]:
return Node(1, 'x')
x = output() # type: IntNode # This is OK (implicit Any)
y: IntNode
y.x = 1
y.x = 'x' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
y.y = 1 # Both are OK (implicit Any)
y.y = 'x'
z = Node(1, 'x') # type: AnyNode
reveal_type(z) # N: Revealed type is "__main__.Node[Any, Any]"
[out]
[case testGenericTypeAliasesAcessingMethods]
from typing import TypeVar, Generic, List
T = TypeVar('T')
class Node(Generic[T]):
def __init__(self, x: T) -> None:
self.x = x
def meth(self) -> T:
return self.x
ListedNode = Node[List[T]]
l: ListedNode[int]
l.x.append(1)
l.meth().append(1)
reveal_type(l.meth()) # N: Revealed type is "builtins.list[builtins.int]"
l.meth().append('x') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
ListedNode[str]([]).x = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "List[str]")
[builtins fixtures/list.pyi]
[case testGenericTypeAliasesSubclassing]
from typing import TypeVar, Generic, Tuple, List
T = TypeVar('T')
class Node(Generic[T]):
def __init__(self, x: T) -> None:
...
TupledNode = Node[Tuple[T, T]]
class D(TupledNode[T]):
...
class L(List[TupledNode[T]]):
...
def f_bad(x: T) -> D[T]:
return D(1) # Error, see out
L[int]().append(Node((1, 1)))
L[int]().append(5) # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "Node[Tuple[int, int]]"
x = D((1, 1)) # type: D[int]
y = D(5) # type: D[int] # E: Argument 1 to "D" has incompatible type "int"; expected "Tuple[int, int]"
def f(x: T) -> D[T]:
return D((x, x))
reveal_type(f('a')) # N: Revealed type is "__main__.D[builtins.str]"
[builtins fixtures/list.pyi]
[out]
main:15: error: Argument 1 to "D" has incompatible type "int"; expected "Tuple[T, T]"
[case testGenericTypeAliasesSubclassingBad]
from typing import TypeVar, Generic, Tuple, Union
T = TypeVar('T')
class Node(Generic[T]):
def __init__(self, x: T) -> None:
...
TupledNode = Node[Tuple[T, T]]
UNode = Union[int, Node[T]]
class C(TupledNode): ... # Same as TupledNode[Any]
class D(TupledNode[T]): ...
class E(Generic[T], UNode[T]): ... # E: Invalid base class "UNode"
reveal_type(D((1, 1))) # N: Revealed type is "__main__.D[builtins.int]"
[builtins fixtures/list.pyi]
[case testGenericTypeAliasesUnion]
from typing import TypeVar, Generic, Union, Any
T = TypeVar('T')
class Node(Generic[T]):
def __init__(self, x: T) -> None:
self.x = x
UNode = Union[int, Node[T]]
x = 1 # type: UNode[int]
x + 1 # E: Unsupported left operand type for + ("Node[int]") \
# N: Left operand is of type "Union[int, Node[int]]"
if not isinstance(x, Node):
x + 1
if not isinstance(x, int):
x.x = 1
x.x = 'a' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
def f(x: T) -> UNode[T]:
if int():
return Node(x)
else:
return 1
reveal_type(f(1)) # N: Revealed type is "Union[builtins.int, __main__.Node[builtins.int]]"
TNode = Union[T, Node[int]]
s = 1 # type: TNode[str] # E: Incompatible types in assignment (expression has type "int", variable has type "Union[str, Node[int]]")
if not isinstance(s, str):
s.x = 1
z = None # type: TNode # Same as TNode[Any]
z.x
z.foo() # E: Item "Node[int]" of "Union[Any, Node[int]]" has no attribute "foo"
[builtins fixtures/isinstance.pyi]
[case testGenericTypeAliasesTuple]
from typing import TypeVar, Tuple
T = TypeVar('T')
SameTP = Tuple[T, T]
IntTP = Tuple[int, T]
def f1(x: T) -> SameTP[T]:
return x, x
a, b, c = f1(1) # E: Need more than 2 values to unpack (3 expected)
x, y = f1(1)
reveal_type(x) # N: Revealed type is "builtins.int"
def f2(x: IntTP[T]) -> IntTP[T]:
return x
f2((1, 2, 3)) # E: Argument 1 to "f2" has incompatible type "Tuple[int, int, int]"; expected "Tuple[int, Never]"
reveal_type(f2((1, 'x'))) # N: Revealed type is "Tuple[builtins.int, builtins.str]"
[builtins fixtures/for.pyi]
[case testGenericTypeAliasesCallable]
from typing import TypeVar, Generic, Callable
T = TypeVar('T')
class Node(Generic[T]):
def __init__(self, x: T) -> None:
...
BadC = Callable[T] # E: Please use "Callable[[<parameters>], <return type>]" or "Callable"
C = Callable[..., T]
C2 = Callable[[T, T], Node[T]]
def make_cb(x: T) -> C[T]:
return lambda *args: x
reveal_type(make_cb(1)) # N: Revealed type is "def (*Any, **Any) -> builtins.int"
def use_cb(arg: T, cb: C2[T]) -> Node[T]:
return cb(arg, arg)
use_cb(1, 1) # E: Argument 2 to "use_cb" has incompatible type "int"; expected "Callable[[int, int], Node[int]]"
my_cb: C2[int]
use_cb('x', my_cb) # E: Argument 2 to "use_cb" has incompatible type "Callable[[int, int], Node[int]]"; expected "Callable[[str, str], Node[str]]"
reveal_type(use_cb(1, my_cb)) # N: Revealed type is "__main__.Node[builtins.int]"
[builtins fixtures/tuple.pyi]
[out]
[case testGenericTypeAliasesPEPBasedExample]
from typing import TypeVar, List, Tuple
T = TypeVar('T', int, bool)
Vec = List[Tuple[T, T]]
vec = [] # type: Vec[bool]
vec.append('x') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "Tuple[bool, bool]"
reveal_type(vec[0]) # N: Revealed type is "Tuple[builtins.bool, builtins.bool]"
def fun1(v: Vec[T]) -> T:
return v[0][0]
def fun2(v: Vec[T], scale: T) -> Vec[T]:
return v
reveal_type(fun1([(1, 1)])) # N: Revealed type is "builtins.int"
fun1(1) # E: Argument 1 to "fun1" has incompatible type "int"; expected "List[Tuple[bool, bool]]"
fun1([(1, 'x')]) # E: Cannot infer type argument 1 of "fun1"
reveal_type(fun2([(1, 1)], 1)) # N: Revealed type is "builtins.list[Tuple[builtins.int, builtins.int]]"
fun2([('x', 'x')], 'x') # E: Value of type variable "T" of "fun2" cannot be "str"
[builtins fixtures/list.pyi]
[case testGenericTypeAliasesImporting]
from typing import TypeVar
from a import Node, TupledNode
T = TypeVar('T')
n: TupledNode[int]
n.x = 1
n.y = (1, 1)
n.y = 'x' # E: Incompatible types in assignment (expression has type "str", variable has type "Tuple[int, int]")
def f(x: Node[T, T]) -> TupledNode[T]:
return Node(x.x, (x.x, x.x))
f(1) # E: Argument 1 to "f" has incompatible type "int"; expected "Node[Never, Never]"
f(Node(1, 'x')) # E: Cannot infer type argument 1 of "f"
reveal_type(Node('x', 'x')) # N: Revealed type is "a.Node[builtins.str, builtins.str]"
[file a.py]
from typing import TypeVar, Generic, Tuple
T = TypeVar('T')
S = TypeVar('S')
class Node(Generic[T, S]):
def __init__(self, x: T, y: S) -> None:
self.x = x
self.y = y
TupledNode = Node[T, Tuple[T, T]]
[builtins fixtures/list.pyi]
[case testGenericTypeAliasesImportingWithoutTypeVar]
from typing import Tuple
from lib import Transform
def int_tf(m: int) -> Transform[int, str]:
def transform(i: int, pos: int) -> Tuple[int, str]:
pass
return transform
var: Transform[int, str]
reveal_type(var) # N: Revealed type is "def (builtins.int, builtins.int) -> Tuple[builtins.int, builtins.str]"
[file lib.py]
from typing import Callable, TypeVar, Tuple
T = TypeVar('T')
R = TypeVar('R')
Transform = Callable[[T, int], Tuple[T, R]]
[builtins fixtures/tuple.pyi]
[out]
[case testGenericTypeAliasesImportingWithoutTypeVarError]
from a import Alias
x: Alias[int, str] # E: Bad number of arguments for type alias, expected: 1, given: 2
reveal_type(x) # N: Revealed type is "builtins.list[builtins.list[Any]]"
[file a.py]
from typing import TypeVar, List
T = TypeVar('T')
Alias = List[List[T]]
[builtins fixtures/list.pyi]
[out]
[case testGenericAliasWithTypeVarsFromDifferentModules]
from mod import Alias, TypeVar
S = TypeVar('S')
NewAlias = Alias[int, int, S, S]
class C: pass
x: NewAlias[str]
reveal_type(x) # N: Revealed type is "builtins.list[Tuple[builtins.int, builtins.int, builtins.str, builtins.str]]"
y: Alias[int, str, C, C]
reveal_type(y) # N: Revealed type is "builtins.list[Tuple[builtins.int, builtins.str, __main__.C, __main__.C]]"
[file mod.py]
from typing import TypeVar, List, Tuple
import a
import b
T = TypeVar('T')
Alias = List[Tuple[T, a.T, b.T, b.B.T]] # alias_tvars here will be ['T', 'a.T', 'b.T', 'b.B.T']
[file a.py]
from typing import TypeVar
T = TypeVar('T')
[file b.py]
from typing import TypeVar
T = TypeVar('T')
class B:
T = TypeVar('T')
[builtins fixtures/list.pyi]
[out]
[case testTypeAliasesResultingInPlainInstance]
from typing import Optional, Union
O = Optional[int]
U = Union[int]
x: O
y: U
reveal_type(x) # N: Revealed type is "Union[builtins.int, None]"
reveal_type(y) # N: Revealed type is "builtins.int"