-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
check-namedtuple.test
1348 lines (1067 loc) · 38.7 KB
/
check-namedtuple.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
[case testNamedTupleUsedAsTuple]
from collections import namedtuple
X = namedtuple('X', 'x y')
x: X
a, b = x
b = x[0]
a = x[1]
a, b, c = x # E: Need more than 2 values to unpack (3 expected)
x[2] # E: Tuple index out of range
[builtins fixtures/tuple.pyi]
[case testNamedTupleWithTupleFieldNamesUsedAsTuple]
from collections import namedtuple
X = namedtuple('X', ('x', 'y'))
x: X
a, b = x
b = x[0]
a = x[1]
a, b, c = x # E: Need more than 2 values to unpack (3 expected)
x[2] # E: Tuple index out of range
[builtins fixtures/tuple.pyi]
[case testNamedTupleNoUnderscoreFields]
from collections import namedtuple
X = namedtuple('X', 'x, _y, _z') # E: "namedtuple()" field names cannot start with an underscore: _y, _z
[builtins fixtures/tuple.pyi]
[case testNamedTupleAccessingAttributes]
from collections import namedtuple
X = namedtuple('X', 'x y')
x: X
x.x
x.y
x.z # E: "X" has no attribute "z"
[builtins fixtures/tuple.pyi]
[case testNamedTupleClassInStub]
import foo
[file foo.pyi]
from typing import NamedTuple
class A(NamedTuple):
x: int
[builtins fixtures/tuple.pyi]
[case testNamedTupleAttributesAreReadOnly]
from collections import namedtuple
X = namedtuple('X', 'x y')
x: X
x.x = 5 # E: Property "x" defined in "X" is read-only
x.y = 5 # E: Property "y" defined in "X" is read-only
x.z = 5 # E: "X" has no attribute "z"
class A(X): pass
a: A
a.x = 5 # E: Property "x" defined in "X" is read-only
a.y = 5 # E: Property "y" defined in "X" is read-only
-- a.z = 5 # not supported yet
[builtins fixtures/tuple.pyi]
[case testTypingNamedTupleAttributesAreReadOnly]
from typing import NamedTuple
from typing_extensions import Protocol
class HasX(Protocol):
x: str
class A(NamedTuple):
x: str
a: HasX = A("foo")
a.x = "bar"
[builtins fixtures/tuple.pyi]
[out]
main:10: error: Incompatible types in assignment (expression has type "A", variable has type "HasX")
main:10: note: Protocol member HasX.x expected settable variable, got read-only attribute
[case testNamedTupleCreateWithPositionalArguments]
from collections import namedtuple
X = namedtuple('X', 'x y')
x = X(1, 'x')
x.x
x.z # E: "X" has no attribute "z"
x = X(1) # E: Missing positional argument "y" in call to "X"
x = X(1, 2, 3) # E: Too many arguments for "X"
[builtins fixtures/tuple.pyi]
[case testCreateNamedTupleWithKeywordArguments]
from collections import namedtuple
X = namedtuple('X', 'x y')
x = X(x=1, y='x')
x = X(1, y='x')
x = X(x=1, z=1) # E: Unexpected keyword argument "z" for "X"
x = X(y=1) # E: Missing positional argument "x" in call to "X"
[builtins fixtures/tuple.pyi]
[case testNamedTupleCreateAndUseAsTuple]
from collections import namedtuple
X = namedtuple('X', 'x y')
x = X(1, 'x')
a, b = x
a, b, c = x # E: Need more than 2 values to unpack (3 expected)
[builtins fixtures/tuple.pyi]
[case testNamedTupleAdditionalArgs]
from collections import namedtuple
A = namedtuple('A', 'a b')
B = namedtuple('B', 'a b', rename=1)
C = namedtuple('C', 'a b', rename='not a bool')
D = namedtuple('D', 'a b', unrecognized_arg=False)
E = namedtuple('E', 'a b', 0)
[builtins fixtures/bool.pyi]
[out]
main:5: error: Argument "rename" to "namedtuple" has incompatible type "str"; expected "int"
main:6: error: Unexpected keyword argument "unrecognized_arg" for "namedtuple"
<ROOT>/test-data/unit/lib-stub/collections.pyi:3: note: "namedtuple" defined here
main:7: error: Too many positional arguments for "namedtuple"
[case testNamedTupleDefaults]
# flags: --python-version 3.7
from collections import namedtuple
X = namedtuple('X', ['x', 'y'], defaults=(1,))
X() # E: Missing positional argument "x" in call to "X"
X(0) # ok
X(0, 1) # ok
X(0, 1, 2) # E: Too many arguments for "X"
Y = namedtuple('Y', ['x', 'y'], defaults=(1, 2, 3)) # E: Too many defaults given in call to "namedtuple()"
Z = namedtuple('Z', ['x', 'y'], defaults='not a tuple') # E: List or tuple literal expected as the defaults argument to namedtuple() # E: Argument "defaults" to "namedtuple" has incompatible type "str"; expected "Optional[Iterable[Any]]"
[builtins fixtures/list.pyi]
[case testNamedTupleWithItemTypes]
from typing import NamedTuple
N = NamedTuple('N', [('a', int),
('b', str)])
n = N(1, 'x')
s = n.a # type: str # E: Incompatible types in assignment (expression has type "int", \
variable has type "str")
i = n.b # type: int # E: Incompatible types in assignment (expression has type "str", \
variable has type "int")
x, y = n
if int():
x = y # E: Incompatible types in assignment (expression has type "str", variable has type "int")
[targets __main__, __main__.N.__new__, __main__.N._asdict, __main__.N._make, __main__.N._replace]
[builtins fixtures/tuple.pyi]
[case testNamedTupleWithTupleFieldNamesWithItemTypes]
from typing import NamedTuple
N = NamedTuple('N', (('a', int),
('b', str)))
n = N(1, 'x')
s = n.a # type: str # E: Incompatible types in assignment (expression has type "int", \
variable has type "str")
i = n.b # type: int # E: Incompatible types in assignment (expression has type "str", \
variable has type "int")
x, y = n
if int():
x = y # E: Incompatible types in assignment (expression has type "str", variable has type "int")
[builtins fixtures/tuple.pyi]
[case testNamedTupleConstructorArgumentTypes]
from typing import NamedTuple
N = NamedTuple('N', [('a', int),
('b', str)])
n = N('x', 'x') # E: Argument 1 to "N" has incompatible type "str"; expected "int"
n = N(1, b=2) # E: Argument "b" to "N" has incompatible type "int"; expected "str"
N(1, 'x')
N(b='x', a=1)
[builtins fixtures/tuple.pyi]
[case testNamedTupleAsBaseClass]
from typing import NamedTuple
N = NamedTuple('N', [('a', int),
('b', str)])
class X(N):
pass
x = X(1, 2) # E: Argument 2 to "X" has incompatible type "int"; expected "str"
s = ''
i = 0
if int():
s = x.a # E: Incompatible types in assignment (expression has type "int", variable has type "str")
if int():
i, s = x
if int():
s, s = x # E: Incompatible types in assignment (expression has type "int", variable has type "str")
[builtins fixtures/tuple.pyi]
[case testNamedTupleAsBaseClass2]
from typing import NamedTuple
class X(NamedTuple('N', [('a', int),
('b', str)])):
pass
x = X(1, 2) # E: Argument 2 to "X" has incompatible type "int"; expected "str"
s = ''
i = 0
if int():
s = x.a # E: Incompatible types in assignment (expression has type "int", variable has type "str")
if int():
i, s = x
if int():
s, s = x # E: Incompatible types in assignment (expression has type "int", variable has type "str")
[builtins fixtures/tuple.pyi]
[case testNamedTuplesTwoAsBaseClasses]
from typing import NamedTuple
A = NamedTuple('A', [('a', int)])
B = NamedTuple('B', [('a', int)])
class X(A, B): # E: Class has two incompatible bases derived from tuple
pass
[builtins fixtures/tuple.pyi]
[case testNamedTuplesTwoAsBaseClasses2]
from typing import NamedTuple
A = NamedTuple('A', [('a', int)])
class X(A, NamedTuple('B', [('a', int)])): # E: Class has two incompatible bases derived from tuple
pass
[builtins fixtures/tuple.pyi]
[case testNamedTupleSelfTypeWithNamedTupleAsBase]
from typing import NamedTuple
A = NamedTuple('A', [('a', int), ('b', str)])
class B(A):
def f(self, x: int) -> None:
self.f(self.a)
self.f(self.b) # E: Argument 1 to "f" of "B" has incompatible type "str"; expected "int"
i = 0
s = ''
if int():
i, s = self
i, i = self # E: Incompatible types in assignment (expression has type "str", \
variable has type "int")
[builtins fixtures/tuple.pyi]
[out]
[case testNamedTupleTypeReferenceToClassDerivedFrom]
from typing import NamedTuple
A = NamedTuple('A', [('a', int), ('b', str)])
class B(A):
def f(self, x: 'B') -> None:
i = 0
s = ''
if int():
self = x
i, s = x
i, s = x.a, x.b
i, s = x.a, x.a # E: Incompatible types in assignment (expression has type "int", \
variable has type "str")
i, i = self # E: Incompatible types in assignment (expression has type "str", \
variable has type "int")
[builtins fixtures/tuple.pyi]
[out]
[case testNamedTupleSubtyping]
from typing import NamedTuple, Tuple
A = NamedTuple('A', [('a', int), ('b', str)])
class B(A): pass
a = A(1, '')
b = B(1, '')
t: Tuple[int, str]
if int():
b = a # E: Incompatible types in assignment (expression has type "A", variable has type "B")
if int():
a = t # E: Incompatible types in assignment (expression has type "Tuple[int, str]", variable has type "A")
if int():
b = t # E: Incompatible types in assignment (expression has type "Tuple[int, str]", variable has type "B")
if int():
t = a
if int():
t = (1, '')
if int():
t = b
if int():
a = b
[builtins fixtures/tuple.pyi]
[case testNamedTupleSimpleTypeInference]
from typing import NamedTuple, Tuple
A = NamedTuple('A', [('a', int)])
l = [A(1), A(2)]
a = A(1)
if int():
a = l[0]
(i,) = l[0]
if int():
i, i = l[0] # E: Need more than 1 value to unpack (2 expected)
if int():
l = [A(1)]
if int():
a = (1,) # E: Incompatible types in assignment (expression has type "Tuple[int]", \
variable has type "A")
[builtins fixtures/list.pyi]
[case testNamedTupleMissingClassAttribute]
import collections
MyNamedTuple = collections.namedtuple('MyNamedTuple', ['spam', 'eggs'])
MyNamedTuple.x # E: "Type[MyNamedTuple]" has no attribute "x"
[builtins fixtures/list.pyi]
[case testNamedTupleEmptyItems]
from typing import NamedTuple
A = NamedTuple('A', [])
[builtins fixtures/tuple.pyi]
[case testNamedTupleProperty]
from typing import NamedTuple
A = NamedTuple('A', [('a', int)])
class B(A):
@property
def b(self) -> int:
return self.a
class C(B): pass
B(1).b
C(2).b
[builtins fixtures/property.pyi]
[case testNamedTupleAsDict]
from collections import namedtuple
X = namedtuple('X', ['x', 'y'])
x: X
reveal_type(x._asdict()) # N: Revealed type is "builtins.dict[builtins.str, Any]"
[builtins fixtures/dict.pyi]
[case testNamedTupleReplace]
from collections import namedtuple
X = namedtuple('X', ['x', 'y'])
x: X
reveal_type(x._replace()) # N: Revealed type is "Tuple[Any, Any, fallback=__main__.X]"
x._replace(y=5)
x._replace(x=3)
x._replace(x=3, y=5)
x._replace(z=5) # E: Unexpected keyword argument "z" for "_replace" of "X"
x._replace(5) # E: Too many positional arguments for "_replace" of "X"
[builtins fixtures/list.pyi]
[case testNamedTupleReplaceAsClass]
# flags: --no-strict-optional
from collections import namedtuple
X = namedtuple('X', ['x', 'y'])
x = None # type: X
X._replace(x, x=1, y=2)
X._replace(x=1, y=2) # E: Missing positional argument "_self" in call to "_replace" of "X"
[builtins fixtures/list.pyi]
[case testNamedTupleReplaceTyped]
from typing import NamedTuple
X = NamedTuple('X', [('x', int), ('y', str)])
x: X
reveal_type(x._replace()) # N: Revealed type is "Tuple[builtins.int, builtins.str, fallback=__main__.X]"
x._replace(x=5)
x._replace(y=5) # E: Argument "y" to "_replace" of "X" has incompatible type "int"; expected "str"
[builtins fixtures/tuple.pyi]
[case testNamedTupleMake]
from typing import NamedTuple
X = NamedTuple('X', [('x', int), ('y', str)])
reveal_type(X._make([5, 'a'])) # N: Revealed type is "Tuple[builtins.int, builtins.str, fallback=__main__.X]"
X._make('a b') # E: Argument 1 to "_make" of "X" has incompatible type "str"; expected "Iterable[Any]"
-- # FIX: not a proper class method
-- x: X
-- reveal_type(x._make([5, 'a'])) # N: Revealed type is "Tuple[builtins.int, builtins.str, fallback=__main__.X]"
-- x._make('a b') # E: Argument 1 to "_make" of "X" has incompatible type "str"; expected Iterable[Any]
[builtins fixtures/list.pyi]
[case testNamedTupleFields]
from typing import NamedTuple
X = NamedTuple('X', [('x', int), ('y', str)])
reveal_type(X._fields) # N: Revealed type is "Tuple[builtins.str, builtins.str]"
[builtins fixtures/tuple.pyi]
[case testNamedTupleSource]
from typing import NamedTuple
X = NamedTuple('X', [('x', int), ('y', str)])
reveal_type(X._source) # N: Revealed type is "builtins.str"
x: X
reveal_type(x._source) # N: Revealed type is "builtins.str"
[builtins fixtures/tuple.pyi]
[case testNamedTupleUnit]
from typing import NamedTuple
X = NamedTuple('X', [])
x = X() # type: X
x._replace()
x._fields[0] # E: Tuple index out of range
[builtins fixtures/tuple.pyi]
[case testNamedTupleJoinNamedTuple]
from typing import NamedTuple
X = NamedTuple('X', [('x', int), ('y', str)])
Y = NamedTuple('Y', [('x', int), ('y', str)])
reveal_type([X(3, 'b'), Y(1, 'a')]) # N: Revealed type is "builtins.list[Tuple[builtins.int, builtins.str]]"
[builtins fixtures/list.pyi]
[case testNamedTupleJoinTuple]
from typing import NamedTuple, Tuple
X = NamedTuple('X', [('x', int), ('y', str)])
reveal_type([(3, 'b'), X(1, 'a')]) # N: Revealed type is "builtins.list[Tuple[builtins.int, builtins.str]]"
reveal_type([X(1, 'a'), (3, 'b')]) # N: Revealed type is "builtins.list[Tuple[builtins.int, builtins.str]]"
[builtins fixtures/list.pyi]
[case testNamedTupleFieldTypes]
from typing import NamedTuple
X = NamedTuple('X', [('x', int), ('y', str)])
reveal_type(X._field_types) # N: Revealed type is "builtins.dict[builtins.str, Any]"
x: X
reveal_type(x._field_types) # N: Revealed type is "builtins.dict[builtins.str, Any]"
[builtins fixtures/dict.pyi]
[case testNamedTupleAndOtherSuperclass]
from typing import NamedTuple
class A: pass
def f(x: A) -> None: pass
class B(NamedTuple('B', []), A): pass
f(B())
x: A
if int():
x = B()
# Sanity check: fail if baseclass does not match
class C: pass
def g(x: C) -> None: pass
class D(NamedTuple('D', []), A): pass
g(D()) # E: Argument 1 to "g" has incompatible type "D"; expected "C"
y: C
if int():
y = D() # E: Incompatible types in assignment (expression has type "D", variable has type "C")
[builtins fixtures/tuple.pyi]
[case testNamedTupleSelfTypeMethod]
from typing import TypeVar, NamedTuple
T = TypeVar('T', bound='A')
class A(NamedTuple('A', [('x', str)])):
def member(self: T) -> T:
return self
class B(A):
pass
a: A
a = A('').member()
b: B
b = B('').member()
a = B('')
a = B('').member()
[builtins fixtures/tuple.pyi]
[case testNamedTupleSelfTypeReplace]
from typing import NamedTuple, TypeVar
A = NamedTuple('A', [('x', str)])
reveal_type(A('hello')._replace(x='')) # N: Revealed type is "Tuple[builtins.str, fallback=__main__.A]"
a: A
a = A('hello')._replace(x='')
class B(A):
pass
reveal_type(B('hello')._replace(x='')) # N: Revealed type is "Tuple[builtins.str, fallback=__main__.B]"
b: B
b = B('hello')._replace(x='')
[builtins fixtures/tuple.pyi]
[case testNamedTupleSelfTypeMake]
from typing import NamedTuple, TypeVar
A = NamedTuple('A', [('x', str)])
reveal_type(A._make([''])) # N: Revealed type is "Tuple[builtins.str, fallback=__main__.A]"
a = A._make(['']) # type: A
class B(A):
pass
reveal_type(B._make([''])) # N: Revealed type is "Tuple[builtins.str, fallback=__main__.B]"
b = B._make(['']) # type: B
[builtins fixtures/list.pyi]
[case testNamedTupleIncompatibleRedefinition]
from typing import NamedTuple
class Crash(NamedTuple):
count: int # E: Incompatible types in assignment (expression has type "int", base class "tuple" defined the type as "Callable[[Tuple[int, ...], object], int]")
[builtins fixtures/tuple.pyi]
[case testNamedTupleInClassNamespace]
# https://github.com/python/mypy/pull/2553#issuecomment-266474341
from typing import NamedTuple
class C:
def f(self):
A = NamedTuple('A', [('x', int)])
def g(self):
A = NamedTuple('A', [('y', int)])
C.A # E: "Type[C]" has no attribute "A"
[builtins fixtures/tuple.pyi]
[case testNamedTupleInFunction]
from typing import NamedTuple
def f() -> None:
A = NamedTuple('A', [('x', int)])
A # E: Name "A" is not defined
[builtins fixtures/tuple.pyi]
[case testNamedTupleForwardAsUpperBound]
# flags: --disable-error-code=used-before-def
from typing import NamedTuple, TypeVar, Generic
T = TypeVar('T', bound='M')
class G(Generic[T]):
x: T
yb: G[int] # E: Type argument "int" of "G" must be a subtype of "M"
yg: G[M]
reveal_type(G[M]().x.x) # N: Revealed type is "builtins.int"
reveal_type(G[M]().x[0]) # N: Revealed type is "builtins.int"
M = NamedTuple('M', [('x', int)])
[builtins fixtures/tuple.pyi]
[out]
[case testNamedTupleWithImportCycle]
import a
[file a.py]
from collections import namedtuple
from b import f
N = namedtuple('N', 'a')
class X(N): pass
[file b.py]
import a
def f(x: a.X) -> None:
reveal_type(x)
x = a.X(1)
reveal_type(x)
[builtins fixtures/tuple.pyi]
[out]
tmp/b.py:4: note: Revealed type is "Tuple[Any, fallback=a.X]"
tmp/b.py:6: note: Revealed type is "Tuple[Any, fallback=a.X]"
[case testNamedTupleWithImportCycle2]
import a
[file a.py]
from collections import namedtuple
from b import f
N = namedtuple('N', 'a')
[file b.py]
import a
def f(x: a.N) -> None:
reveal_type(x)
if int():
x = a.N(1)
reveal_type(x)
[builtins fixtures/tuple.pyi]
[out]
tmp/b.py:4: note: Revealed type is "Tuple[Any, fallback=a.N]"
tmp/b.py:7: note: Revealed type is "Tuple[Any, fallback=a.N]"
[case testSimpleSelfReferentialNamedTuple]
# flags: --disable-recursive-aliases
from typing import NamedTuple
class MyNamedTuple(NamedTuple):
parent: 'MyNamedTuple' # E: Cannot resolve name "MyNamedTuple" (possible cyclic definition)
def bar(nt: MyNamedTuple) -> MyNamedTuple:
return nt
x: MyNamedTuple
reveal_type(x.parent) # N: Revealed type is "Any"
[builtins fixtures/tuple.pyi]
-- Some crazy self-referential named tuples and types dicts
-- to be sure that everything works
[case testCrossFileNamedTupleForwardRefs]
import a
[file a.py]
import b
from typing import Any, NamedTuple
class A:
def a(self, b: 'b.B') -> str:
return 'a'
ATuple = NamedTuple('ATuple', [('a', Any)])
[file b.py]
import a
class B:
def b(self, a: 'a.A') -> str:
return 'b'
def aWithTuple(self, atuple: 'a.ATuple') -> str:
return 'a'
[builtins fixtures/tuple.pyi]
[out]
[case testSelfRefNT1]
# flags: --disable-recursive-aliases
from typing import Tuple, NamedTuple
Node = NamedTuple('Node', [
('name', str),
('children', Tuple['Node', ...]), # E: Cannot resolve name "Node" (possible cyclic definition)
])
n: Node
reveal_type(n) # N: Revealed type is "Tuple[builtins.str, builtins.tuple[Any, ...], fallback=__main__.Node]"
[builtins fixtures/tuple.pyi]
[case testSelfRefNT2]
# flags: --disable-recursive-aliases
from typing import Tuple, NamedTuple
A = NamedTuple('A', [
('x', str),
('y', Tuple['B', ...]), # E: Cannot resolve name "B" (possible cyclic definition)
])
class B(NamedTuple):
x: A
y: int
n: A
reveal_type(n) # N: Revealed type is "Tuple[builtins.str, builtins.tuple[Any, ...], fallback=__main__.A]"
[builtins fixtures/tuple.pyi]
[case testSelfRefNT3]
# flags: --disable-recursive-aliases
from typing import NamedTuple, Tuple
class B(NamedTuple):
x: Tuple[A, int] # E: Cannot resolve name "A" (possible cyclic definition)
y: int
A = NamedTuple('A', [
('x', str),
('y', 'B'),
])
n: B
m: A
reveal_type(n.x) # N: Revealed type is "Tuple[Any, builtins.int]"
reveal_type(m[0]) # N: Revealed type is "builtins.str"
lst = [m, n]
reveal_type(lst[0]) # N: Revealed type is "Tuple[builtins.object, builtins.object]"
[builtins fixtures/tuple.pyi]
[case testSelfRefNT4]
# flags: --disable-recursive-aliases
from typing import NamedTuple
class B(NamedTuple):
x: A # E: Cannot resolve name "A" (possible cyclic definition)
y: int
class A(NamedTuple):
x: str
y: B
n: A
reveal_type(n.y[0]) # N: Revealed type is "Any"
[builtins fixtures/tuple.pyi]
[case testSelfRefNT5]
# flags: --disable-recursive-aliases
from typing import NamedTuple
B = NamedTuple('B', [
('x', A), # E: Cannot resolve name "A" (possible cyclic definition) # E: Name "A" is used before definition
('y', int),
])
A = NamedTuple('A', [
('x', str),
('y', 'B'),
])
n: A
def f(m: B) -> None: pass
reveal_type(n) # N: Revealed type is "Tuple[builtins.str, Tuple[Any, builtins.int, fallback=__main__.B], fallback=__main__.A]"
reveal_type(f) # N: Revealed type is "def (m: Tuple[Any, builtins.int, fallback=__main__.B])"
[builtins fixtures/tuple.pyi]
[case testRecursiveNamedTupleInBases]
# flags: --disable-recursive-aliases
from typing import List, NamedTuple, Union
Exp = Union['A', 'B'] # E: Cannot resolve name "Exp" (possible cyclic definition) \
# E: Cannot resolve name "A" (possible cyclic definition)
class A(NamedTuple('A', [('attr', List[Exp])])): pass
class B(NamedTuple('B', [('val', object)])): pass
def my_eval(exp: Exp) -> int:
reveal_type(exp) # N: Revealed type is "Union[Any, Tuple[builtins.object, fallback=__main__.B]]"
if isinstance(exp, A):
my_eval(exp[0][0])
return my_eval(exp.attr[0])
if isinstance(exp, B):
return exp.val # E: Incompatible return value type (got "object", expected "int")
return 0
my_eval(A([B(1), B(2)])) # OK
[builtins fixtures/isinstancelist.pyi]
[out]
[case testNamedTupleImportCycle]
import b
[file a.py]
class C:
pass
from b import tp
x: tp
reveal_type(x.x) # N: Revealed type is "builtins.int"
reveal_type(tp) # N: Revealed type is "def (x: builtins.int) -> Tuple[builtins.int, fallback=b.tp]"
tp('x') # E: Argument 1 to "tp" has incompatible type "str"; expected "int"
[file b.py]
from a import C
from typing import NamedTuple
tp = NamedTuple('tp', [('x', int)])
[builtins fixtures/tuple.pyi]
[out]
[case testSubclassOfRecursiveNamedTuple]
# flags: --disable-recursive-aliases
from typing import List, NamedTuple
class Command(NamedTuple):
subcommands: List['Command'] # E: Cannot resolve name "Command" (possible cyclic definition)
class HelpCommand(Command):
pass
hc = HelpCommand(subcommands=[])
reveal_type(hc) # N: Revealed type is "Tuple[builtins.list[Any], fallback=__main__.HelpCommand]"
[builtins fixtures/list.pyi]
[out]
[case testUnsafeOverlappingNamedTuple]
from typing import NamedTuple
class Real(NamedTuple):
def __sub__(self, other: Real) -> str: return ""
class Fraction(Real):
def __rsub__(self, other: Real) -> Real: return other # E: Signatures of "__rsub__" of "Fraction" and "__sub__" of "Real" are unsafely overlapping
[builtins fixtures/tuple.pyi]
[case testForwardReferenceInNamedTuple]
from typing import NamedTuple
class A(NamedTuple):
b: 'B'
x: int
class B:
pass
[builtins fixtures/tuple.pyi]
[case testTypeNamedTupleClassmethod]
from typing import Type, NamedTuple
class D(NamedTuple):
@classmethod
def f(cls) -> None: pass
d: Type[D]
d.g() # E: "Type[D]" has no attribute "g"
d.f()
[builtins fixtures/classmethod.pyi]
[case testTypeNamedTupleCall]
from typing import NamedTuple
Thing = NamedTuple('Thing', [('s', str), ('n', int)])
class CallableTuple(Thing):
def __call__(self) -> None:
pass
o = CallableTuple('hello ', 12)
o()
[builtins fixtures/tuple.pyi]
[case testNamedTupleSubclassMulti]
from typing import NamedTuple
class Base:
pass
class BaseTuple(NamedTuple):
value: float
class MyTuple(BaseTuple, Base):
pass
def f(o: Base) -> None:
if isinstance(o, MyTuple):
reveal_type(o.value) # N: Revealed type is "builtins.float"
[builtins fixtures/isinstance.pyi]
[out]
[case testNamedTupleNew]
from typing import NamedTuple
Base = NamedTuple('Base', [('param', int)])
class Child(Base):
def __new__(cls, param: int = 1) -> 'Child':
return Base.__new__(cls, param)
Base(param=10)
Child(param=10)
[builtins fixtures/tuple.pyi]
[case testNamedTupleClassMethodWithGenericReturnValue]
from typing import TypeVar, Type, NamedTuple
T = TypeVar('T', bound='Parent')
class Parent(NamedTuple):
x: str
@classmethod
def class_method(cls: Type[T]) -> T:
return cls(x='text')
class Child(Parent):
pass
reveal_type(Child.class_method()) # N: Revealed type is "Tuple[builtins.str, fallback=__main__.Child]"
[builtins fixtures/classmethod.pyi]
[case testNamedTupleAsConditionalStrictOptionalDisabled]
# flags: --no-strict-optional --warn-unreachable
from typing import NamedTuple
class C(NamedTuple):
a: int
b: str
a: C
if not a:
1() # E: "int" not callable
b = (1, 2)
if not b:
''() # E: "str" not callable
[builtins fixtures/tuple.pyi]
[case testNamedTupleDoubleForward]
# flags: --disable-error-code=used-before-def
from typing import Union, Mapping, NamedTuple
class MyBaseTuple(NamedTuple):
base_field_1: int
base_field_2: int
MyBaseTupleMapping = Mapping[MyBaseTuple, int]
MyTupleUnion = Union[MyTupleA, MyTupleB]
class MyTupleA(NamedTuple):
field_1: MyBaseTupleMapping
field_2: MyBaseTuple
class MyTupleB(NamedTuple):
field_1: MyBaseTupleMapping
field_2: MyBaseTuple
u: MyTupleUnion
reveal_type(u.field_1) # N: Revealed type is "typing.Mapping[Tuple[builtins.int, builtins.int, fallback=__main__.MyBaseTuple], builtins.int]"
reveal_type(u.field_2) # N: Revealed type is "Tuple[builtins.int, builtins.int, fallback=__main__.MyBaseTuple]"
reveal_type(u[0]) # N: Revealed type is "typing.Mapping[Tuple[builtins.int, builtins.int, fallback=__main__.MyBaseTuple], builtins.int]"
reveal_type(u[1]) # N: Revealed type is "Tuple[builtins.int, builtins.int, fallback=__main__.MyBaseTuple]"
[builtins fixtures/tuple.pyi]
[case testAssignNamedTupleAsAttribute]
from typing import NamedTuple
class A:
def __init__(self) -> None:
self.b = NamedTuple('x', [('s', str), ('n', int)]) # E: NamedTuple type as an attribute is not supported
reveal_type(A().b) # N: Revealed type is "typing.NamedTuple"
[builtins fixtures/tuple.pyi]
[typing fixtures/typing-namedtuple.pyi]
[case testEmptyNamedTupleTypeRepr]
from typing import NamedTuple
N = NamedTuple('N', [])
n: N
reveal_type(N) # N: Revealed type is "def () -> Tuple[(), fallback=__main__.N]"
reveal_type(n) # N: Revealed type is "Tuple[(), fallback=__main__.N]"
[builtins fixtures/tuple.pyi]
[case testNamedTupleWrongfile]
from typing import NamedTuple
from b import Type1
Type2 = NamedTuple('Type2', [('x', Type1)])
[file b.py]
from typing import NamedTuple
def foo():
pass
Type1 = NamedTuple('Type1', [('foo', foo)]) # E: Function "b.foo" is not valid as a type # N: Perhaps you need "Callable[...]" or a callback protocol?
[builtins fixtures/tuple.pyi]
[case testNamedTupleTypeNameMatchesVariableName]
from typing import NamedTuple
from collections import namedtuple
A = NamedTuple('X', [('a', int)]) # E: First argument to namedtuple() should be "A", not "X"
B = namedtuple('X', ['a']) # E: First argument to namedtuple() should be "B", not "X"
C = NamedTuple('X', [('a', 'Y')]) # E: First argument to namedtuple() should be "C", not "X"
class Y: ...
[builtins fixtures/tuple.pyi]
[case testNamedTupleTypeIsASuperTypeOfOtherNamedTuples]
from typing import Tuple, NamedTuple
class Bar(NamedTuple):
name: str = "Bar"
class Baz(NamedTuple):
a: str
b: str
class Biz(Baz): ...
class Other: ...
class Both1(Bar, Other): ...
class Both2(Other, Bar): ...
class Both3(Biz, Other): ...
def print_namedtuple(obj: NamedTuple) -> None:
reveal_type(obj._fields) # N: Revealed type is "builtins.tuple[builtins.str, ...]"
b1: Bar
b2: Baz
b3: Biz
b4: Both1
b5: Both2
b6: Both3
print_namedtuple(b1) # ok
print_namedtuple(b2) # ok
print_namedtuple(b3) # ok
print_namedtuple(b4) # ok
print_namedtuple(b5) # ok
print_namedtuple(b6) # ok