Debian Codegraph @

test-data/unit/check-namedtuple.test

raw
1 [case testNamedTupleUsedAsTuple]
2 from collections import namedtuple
3
4 X = namedtuple('X', 'x y')
5 x: X
6 a, b = x
7 b = x[0]
8 a = x[1]
9 a, b, c = x # E: Need more than 2 values to unpack (3 expected)
10 x[2] # E: Tuple index out of range
11 [builtins fixtures/tuple.pyi]
12
13 [case testNamedTupleWithTupleFieldNamesUsedAsTuple]
14 from collections import namedtuple
15
16 X = namedtuple('X', ('x', 'y'))
17 x: X
18 a, b = x
19 b = x[0]
20 a = x[1]
21 a, b, c = x # E: Need more than 2 values to unpack (3 expected)
22 x[2] # E: Tuple index out of range
23 [builtins fixtures/tuple.pyi]
24
25 [case testNamedTupleInvalidFields]
26 from collections import namedtuple
27
28 X = namedtuple('X', 'x, _y') # E: "namedtuple()" field name "_y" starts with an underscore
29 Y = namedtuple('Y', ['x', '1']) # E: "namedtuple()" field name "1" is not a valid identifier
30 Z = namedtuple('Z', ['x', 'def']) # E: "namedtuple()" field name "def" is a keyword
31 A = namedtuple('A', ['x', 'x']) # E: "namedtuple()" has duplicate field name "x"
32 [builtins fixtures/tuple.pyi]
33
34 [case testNamedTupleAccessingAttributes]
35 from collections import namedtuple
36
37 X = namedtuple('X', 'x y')
38 x: X
39 x.x
40 x.y
41 x.z # E: "X" has no attribute "z"
42 [builtins fixtures/tuple.pyi]
43
44 [case testNamedTupleClassInStub]
45 import foo
46
47 [file foo.pyi]
48 from typing import NamedTuple
49
50 class A(NamedTuple):
51 x: int
52 [builtins fixtures/tuple.pyi]
53
54 [case testNamedTupleAttributesAreReadOnly]
55 from collections import namedtuple
56
57 X = namedtuple('X', 'x y')
58 x: X
59 x.x = 5 # E: Property "x" defined in "X" is read-only
60 x.y = 5 # E: Property "y" defined in "X" is read-only
61 x.z = 5 # E: "X" has no attribute "z"
62
63 class A(X): pass
64 a: A
65 a.x = 5 # E: Property "x" defined in "X" is read-only
66 a.y = 5 # E: Property "y" defined in "X" is read-only
67 -- a.z = 5 # not supported yet
68 [builtins fixtures/tuple.pyi]
69
70
71 [case testTypingNamedTupleAttributesAreReadOnly]
72 from typing import NamedTuple, Protocol
73
74 class HasX(Protocol):
75 x: str
76
77 class A(NamedTuple):
78 x: str
79
80 a: HasX = A("foo")
81 a.x = "bar"
82 [builtins fixtures/tuple.pyi]
83 [out]
84 main:9: error: Incompatible types in assignment (expression has type "A", variable has type "HasX")
85 main:9: note: Protocol member HasX.x expected settable variable, got read-only attribute
86
87
88 [case testNamedTupleCreateWithPositionalArguments]
89 from collections import namedtuple
90
91 X = namedtuple('X', 'x y')
92 x = X(1, 'x')
93 x.x
94 x.z # E: "X" has no attribute "z"
95 x = X(1) # E: Missing positional argument "y" in call to "X"
96 x = X(1, 2, 3) # E: Too many arguments for "X"
97 [builtins fixtures/tuple.pyi]
98
99 [case testCreateNamedTupleWithKeywordArguments]
100 from collections import namedtuple
101
102 X = namedtuple('X', 'x y')
103 x = X(x=1, y='x')
104 x = X(1, y='x')
105 x = X(x=1, z=1) # E: Unexpected keyword argument "z" for "X"
106 x = X(y=1) # E: Missing positional argument "x" in call to "X"
107 [builtins fixtures/tuple.pyi]
108
109 [case testNamedTupleCreateAndUseAsTuple]
110 from collections import namedtuple
111
112 X = namedtuple('X', 'x y')
113 x = X(1, 'x')
114 a, b = x
115 a, b, c = x # E: Need more than 2 values to unpack (3 expected)
116 [builtins fixtures/tuple.pyi]
117
118 [case testNamedTupleAdditionalArgs]
119 from collections import namedtuple
120
121 A = namedtuple('A', 'a b')
122 B = namedtuple('B', 'a b', rename=1)
123 C = namedtuple('C', 'a b', rename='not a bool')
124 D = namedtuple('D', 'a b', unrecognized_arg=False)
125 E = namedtuple('E', 'a b', 0)
126
127 [builtins fixtures/bool.pyi]
128 [out]
129 main:4: error: Boolean literal expected as the "rename" argument to namedtuple()
130 main:5: error: Boolean literal expected as the "rename" argument to namedtuple()
131 main:5: error: Argument "rename" to "namedtuple" has incompatible type "str"; expected "int"
132 main:6: error: Unexpected keyword argument "unrecognized_arg" for "namedtuple"
133 main:6: note: "namedtuple" defined in "collections"
134 main:7: error: Too many positional arguments for "namedtuple"
135 main:7: note: "namedtuple" defined in "collections"
136
137 [case testNamedTupleDefaults]
138 from collections import namedtuple
139
140 X = namedtuple('X', ['x', 'y'], defaults=(1,))
141
142 X() # E: Missing positional argument "x" in call to "X"
143 X(0) # ok
144 X(0, 1) # ok
145 X(0, 1, 2) # E: Too many arguments for "X"
146
147 Y = namedtuple('Y', ['x', 'y'], defaults=(1, 2, 3)) # E: Too many defaults given in call to "namedtuple()"
148 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 "Iterable[Any] | None"
149
150 [builtins fixtures/list.pyi]
151
152 [case testNamedTupleRename]
153 from collections import namedtuple
154
155 X = namedtuple('X', ['abc', 'def'], rename=False) # E: "namedtuple()" field name "def" is a keyword
156 Y = namedtuple('Y', ['x', 'x', 'def', '42', '_x'], rename=True)
157 y = Y(x=0, _1=1, _2=2, _3=3, _4=4)
158 reveal_type(y.x) # N: Revealed type is "Any"
159 reveal_type(y._1) # N: Revealed type is "Any"
160 reveal_type(y._2) # N: Revealed type is "Any"
161 reveal_type(y._3) # N: Revealed type is "Any"
162 reveal_type(y._4) # N: Revealed type is "Any"
163 y._0 # E: "Y" has no attribute "_0"
164 y._5 # E: "Y" has no attribute "_5"
165 y._x # E: "Y" has no attribute "_x"
166
167 [builtins fixtures/list.pyi]
168
169 [case testNamedTupleWithItemTypes]
170 from typing import NamedTuple
171 N = NamedTuple('N', [('a', int),
172 ('b', str)])
173 n = N(1, 'x')
174 s = n.a # type: str # E: Incompatible types in assignment (expression has type "int", \
175 variable has type "str")
176 i = n.b # type: int # E: Incompatible types in assignment (expression has type "str", \
177 variable has type "int")
178 x, y = n
179 if int():
180 x = y # E: Incompatible types in assignment (expression has type "str", variable has type "int")
181 [targets __main__, __main__.N.__new__, __main__.N._asdict, __main__.N._make, __main__.N._replace]
182 [builtins fixtures/tuple.pyi]
183
184
185 [case testNamedTupleWithTupleFieldNamesWithItemTypes]
186 from typing import NamedTuple
187 N = NamedTuple('N', (('a', int),
188 ('b', str)))
189 n = N(1, 'x')
190 s = n.a # type: str # E: Incompatible types in assignment (expression has type "int", \
191 variable has type "str")
192 i = n.b # type: int # E: Incompatible types in assignment (expression has type "str", \
193 variable has type "int")
194 x, y = n
195 if int():
196 x = y # E: Incompatible types in assignment (expression has type "str", variable has type "int")
197 [builtins fixtures/tuple.pyi]
198
199
200 [case testNamedTupleConstructorArgumentTypes]
201 from typing import NamedTuple
202 N = NamedTuple('N', [('a', int),
203 ('b', str)])
204 n = N('x', 'x') # E: Argument 1 to "N" has incompatible type "str"; expected "int"
205 n = N(1, b=2) # E: Argument "b" to "N" has incompatible type "int"; expected "str"
206 N(1, 'x')
207 N(b='x', a=1)
208 [builtins fixtures/tuple.pyi]
209
210 [case testNamedTupleAsBaseClass]
211 from typing import NamedTuple
212 N = NamedTuple('N', [('a', int),
213 ('b', str)])
214 class X(N):
215 pass
216 x = X(1, 2) # E: Argument 2 to "X" has incompatible type "int"; expected "str"
217 s = ''
218 i = 0
219 if int():
220 s = x.a # E: Incompatible types in assignment (expression has type "int", variable has type "str")
221 if int():
222 i, s = x
223 if int():
224 s, s = x # E: Incompatible types in assignment (expression has type "int", variable has type "str")
225 [builtins fixtures/tuple.pyi]
226
227 [case testNamedTupleAsBaseClass2]
228 from typing import NamedTuple
229 class X(NamedTuple('N', [('a', int),
230 ('b', str)])):
231 pass
232 x = X(1, 2) # E: Argument 2 to "X" has incompatible type "int"; expected "str"
233 s = ''
234 i = 0
235 if int():
236 s = x.a # E: Incompatible types in assignment (expression has type "int", variable has type "str")
237 if int():
238 i, s = x
239 if int():
240 s, s = x # E: Incompatible types in assignment (expression has type "int", variable has type "str")
241 [builtins fixtures/tuple.pyi]
242
243
244 [case testNamedTuplesTwoAsBaseClasses]
245 from typing import NamedTuple
246 A = NamedTuple('A', [('a', int)])
247 B = NamedTuple('B', [('a', int)])
248 class X(A, B): # E: Class has two incompatible bases derived from tuple
249 pass
250 [builtins fixtures/tuple.pyi]
251
252
253 [case testNamedTuplesTwoAsBaseClasses2]
254 from typing import NamedTuple
255 A = NamedTuple('A', [('a', int)])
256 class X(A, NamedTuple('B', [('a', int)])): # E: Class has two incompatible bases derived from tuple
257 pass
258 [builtins fixtures/tuple.pyi]
259
260
261 [case testNamedTupleSelfTypeWithNamedTupleAsBase]
262 from typing import NamedTuple
263 A = NamedTuple('A', [('a', int), ('b', str)])
264 class B(A):
265 def f(self, x: int) -> None:
266 self.f(self.a)
267 self.f(self.b) # E: Argument 1 to "f" of "B" has incompatible type "str"; expected "int"
268 i = 0
269 s = ''
270 if int():
271 i, s = self
272 i, i = self # E: Incompatible types in assignment (expression has type "str", \
273 variable has type "int")
274 [builtins fixtures/tuple.pyi]
275
276
277 [out]
278
279 [case testNamedTupleTypeReferenceToClassDerivedFrom]
280 from typing import NamedTuple
281 A = NamedTuple('A', [('a', int), ('b', str)])
282 class B(A):
283 def f(self, x: 'B') -> None:
284 i = 0
285 s = ''
286 if int():
287 self = x
288 i, s = x
289 i, s = x.a, x.b
290 i, s = x.a, x.a # E: Incompatible types in assignment (expression has type "int", \
291 variable has type "str")
292 i, i = self # E: Incompatible types in assignment (expression has type "str", \
293 variable has type "int")
294 [builtins fixtures/tuple.pyi]
295
296 [out]
297
298 [case testNamedTupleSubtyping]
299 from typing import NamedTuple, Tuple
300 A = NamedTuple('A', [('a', int), ('b', str)])
301 class B(A): pass
302 a = A(1, '')
303 b = B(1, '')
304 t: Tuple[int, str]
305 if int():
306 b = a # E: Incompatible types in assignment (expression has type "A", variable has type "B")
307 if int():
308 a = t # E: Incompatible types in assignment (expression has type "tuple[int, str]", variable has type "A")
309 if int():
310 b = t # E: Incompatible types in assignment (expression has type "tuple[int, str]", variable has type "B")
311 if int():
312 t = a
313 if int():
314 t = (1, '')
315 if int():
316 t = b
317 if int():
318 a = b
319 [builtins fixtures/tuple.pyi]
320
321
322 [case testNamedTupleSimpleTypeInference]
323 from typing import NamedTuple, Tuple
324 A = NamedTuple('A', [('a', int)])
325 l = [A(1), A(2)]
326 a = A(1)
327 if int():
328 a = l[0]
329 (i,) = l[0]
330 if int():
331 i, i = l[0] # E: Need more than 1 value to unpack (2 expected)
332 if int():
333 l = [A(1)]
334 if int():
335 a = (1,) # E: Incompatible types in assignment (expression has type "tuple[int]", \
336 variable has type "A")
337 [builtins fixtures/list.pyi]
338
339 [case testNamedTupleMissingClassAttribute]
340 import collections
341 MyNamedTuple = collections.namedtuple('MyNamedTuple', ['spam', 'eggs'])
342 MyNamedTuple.x # E: "type[MyNamedTuple]" has no attribute "x"
343
344 [builtins fixtures/list.pyi]
345
346 [case testNamedTupleEmptyItems]
347 from typing import NamedTuple
348 A = NamedTuple('A', [])
349 [builtins fixtures/tuple.pyi]
350
351
352 [case testNamedTupleProperty]
353 from typing import NamedTuple
354 A = NamedTuple('A', [('a', int)])
355 class B(A):
356 @property
357 def b(self) -> int:
358 return self.a
359 class C(B): pass
360 B(1).b
361 C(2).b
362
363 [builtins fixtures/property.pyi]
364
365 [case testNamedTupleAsDict]
366 from collections import namedtuple
367
368 X = namedtuple('X', ['x', 'y'])
369 x: X
370 reveal_type(x._asdict()) # N: Revealed type is "builtins.dict[builtins.str, Any]"
371
372 [builtins fixtures/dict.pyi]
373
374 [case testNamedTupleReplace]
375 from collections import namedtuple
376
377 X = namedtuple('X', ['x', 'y'])
378 x: X
379 reveal_type(x._replace()) # N: Revealed type is "tuple[Any, Any, fallback=__main__.X]"
380 x._replace(y=5)
381 x._replace(x=3)
382 x._replace(x=3, y=5)
383 x._replace(z=5) # E: Unexpected keyword argument "z" for "_replace" of "X"
384 x._replace(5) # E: Too many positional arguments for "_replace" of "X"
385
386 [builtins fixtures/list.pyi]
387
388 [case testNamedTupleReplaceAsClass]
389 # flags: --no-strict-optional
390 from collections import namedtuple
391
392 X = namedtuple('X', ['x', 'y'])
393 x = None # type: X
394 X._replace(x, x=1, y=2)
395 X._replace(x=1, y=2) # E: Missing positional argument "_self" in call to "_replace" of "X"
396
397 [builtins fixtures/list.pyi]
398
399 [case testNamedTupleReplaceTyped]
400 from typing import NamedTuple
401
402 X = NamedTuple('X', [('x', int), ('y', str)])
403 x: X
404 reveal_type(x._replace()) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=__main__.X]"
405 x._replace(x=5)
406 x._replace(y=5) # E: Argument "y" to "_replace" of "X" has incompatible type "int"; expected "str"
407 [builtins fixtures/tuple.pyi]
408
409 [case testNamedTupleMake]
410 from typing import NamedTuple
411
412 X = NamedTuple('X', [('x', int), ('y', str)])
413 reveal_type(X._make([5, 'a'])) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=__main__.X]"
414 X._make('a b') # E: Argument 1 to "_make" of "X" has incompatible type "str"; expected "Iterable[Any]"
415
416 -- # FIX: not a proper class method
417 -- x: X
418 -- reveal_type(x._make([5, 'a'])) # N: Revealed type is "Tuple[builtins.int, builtins.str, fallback=__main__.X]"
419 -- x._make('a b') # E: Argument 1 to "_make" of "X" has incompatible type "str"; expected Iterable[Any]
420
421 [builtins fixtures/list.pyi]
422
423 [case testNamedTupleFields]
424 from typing import NamedTuple
425
426 X = NamedTuple('X', [('x', int), ('y', str)])
427 reveal_type(X._fields) # N: Revealed type is "tuple[builtins.str, builtins.str]"
428 [builtins fixtures/tuple.pyi]
429
430 [case testNamedTupleSource]
431 from typing import NamedTuple
432
433 X = NamedTuple('X', [('x', int), ('y', str)])
434 reveal_type(X._source) # N: Revealed type is "builtins.str"
435 x: X
436 reveal_type(x._source) # N: Revealed type is "builtins.str"
437 [builtins fixtures/tuple.pyi]
438
439 [case testNamedTupleUnit]
440 from typing import NamedTuple
441
442 X = NamedTuple('X', [])
443 x = X() # type: X
444 x._replace()
445 x._fields[0] # E: Tuple index out of range
446 [builtins fixtures/tuple.pyi]
447
448 [case testNamedTupleJoinNamedTuple]
449 from typing import NamedTuple
450
451 X = NamedTuple('X', [('x', int), ('y', str)])
452 Y = NamedTuple('Y', [('x', int), ('y', str)])
453 reveal_type([X(3, 'b'), Y(1, 'a')]) # N: Revealed type is "builtins.list[tuple[builtins.int, builtins.str]]"
454
455 [builtins fixtures/list.pyi]
456
457 [case testNamedTupleJoinTuple]
458 from typing import NamedTuple, Tuple
459
460 X = NamedTuple('X', [('x', int), ('y', str)])
461 reveal_type([(3, 'b'), X(1, 'a')]) # N: Revealed type is "builtins.list[tuple[builtins.int, builtins.str]]"
462 reveal_type([X(1, 'a'), (3, 'b')]) # N: Revealed type is "builtins.list[tuple[builtins.int, builtins.str]]"
463
464 [builtins fixtures/list.pyi]
465
466 [case testNamedTupleFieldTypes]
467 from typing import NamedTuple
468
469 X = NamedTuple('X', [('x', int), ('y', str)])
470 reveal_type(X._field_types) # N: Revealed type is "builtins.dict[builtins.str, Any]"
471 x: X
472 reveal_type(x._field_types) # N: Revealed type is "builtins.dict[builtins.str, Any]"
473
474 [builtins fixtures/dict.pyi]
475
476 [case testNamedTupleAndOtherSuperclass]
477 from typing import NamedTuple
478
479 class A: pass
480 def f(x: A) -> None: pass
481
482 class B(NamedTuple('B', []), A): pass
483 f(B())
484 x: A
485 if int():
486 x = B()
487
488 # Sanity check: fail if baseclass does not match
489 class C: pass
490 def g(x: C) -> None: pass
491 class D(NamedTuple('D', []), A): pass
492
493 g(D()) # E: Argument 1 to "g" has incompatible type "D"; expected "C"
494 y: C
495 if int():
496 y = D() # E: Incompatible types in assignment (expression has type "D", variable has type "C")
497 [builtins fixtures/tuple.pyi]
498
499 [case testNamedTupleSelfTypeMethod]
500 from typing import TypeVar, NamedTuple
501
502 T = TypeVar('T', bound='A')
503
504 class A(NamedTuple('A', [('x', str)])):
505 def member(self: T) -> T:
506 return self
507
508 class B(A):
509 pass
510
511 a: A
512 a = A('').member()
513 b: B
514 b = B('').member()
515 a = B('')
516 a = B('').member()
517 [builtins fixtures/tuple.pyi]
518
519 [case testNamedTupleSelfTypeReplace]
520 from typing import NamedTuple, TypeVar
521 A = NamedTuple('A', [('x', str)])
522 reveal_type(A('hello')._replace(x='')) # N: Revealed type is "tuple[builtins.str, fallback=__main__.A]"
523 a: A
524 a = A('hello')._replace(x='')
525
526 class B(A):
527 pass
528
529 reveal_type(B('hello')._replace(x='')) # N: Revealed type is "tuple[builtins.str, fallback=__main__.B]"
530 b: B
531 b = B('hello')._replace(x='')
532 [builtins fixtures/tuple.pyi]
533
534 [case testNamedTupleSelfTypeMake]
535 from typing import NamedTuple, TypeVar
536 A = NamedTuple('A', [('x', str)])
537 reveal_type(A._make([''])) # N: Revealed type is "tuple[builtins.str, fallback=__main__.A]"
538 a = A._make(['']) # type: A
539
540 class B(A):
541 pass
542
543 reveal_type(B._make([''])) # N: Revealed type is "tuple[builtins.str, fallback=__main__.B]"
544 b = B._make(['']) # type: B
545
546 [builtins fixtures/list.pyi]
547
548 [case testNamedTupleIncompatibleRedefinition]
549 from typing import NamedTuple
550 class Crash(NamedTuple):
551 count: int # E: Incompatible types in assignment (expression has type "int", base class "tuple" defined the type as "Callable[[object], int]")
552 [builtins fixtures/tuple.pyi]
553
554 [case testNamedTupleInClassNamespace]
555 # https://github.com/python/mypy/pull/2553#issuecomment-266474341
556 from typing import NamedTuple
557 class C:
558 def f(self):
559 A = NamedTuple('A', [('x', int)])
560 def g(self):
561 A = NamedTuple('A', [('y', int)])
562 C.A # E: "type[C]" has no attribute "A"
563 [builtins fixtures/tuple.pyi]
564
565 [case testNamedTupleInFunction]
566 from typing import NamedTuple
567 def f() -> None:
568 A = NamedTuple('A', [('x', int)])
569 A # E: Name "A" is not defined
570 [builtins fixtures/tuple.pyi]
571
572 [case testNamedTupleForwardAsUpperBound]
573 # flags: --disable-error-code=used-before-def
574 from typing import NamedTuple, TypeVar, Generic
575 T = TypeVar('T', bound='M')
576 class G(Generic[T]):
577 x: T
578
579 yb: G[int] # E: Type argument "int" of "G" must be a subtype of "M"
580 yg: G[M]
581 reveal_type(G[M]().x.x) # N: Revealed type is "builtins.int"
582 reveal_type(G[M]().x[0]) # N: Revealed type is "builtins.int"
583
584 M = NamedTuple('M', [('x', int)])
585 [builtins fixtures/tuple.pyi]
586 [out]
587
588 [case testNamedTupleWithImportCycle]
589 import a
590 [file a.py]
591 from collections import namedtuple
592 from b import f
593
594 N = namedtuple('N', 'a')
595
596 class X(N): pass
597 [file b.py]
598 import a
599
600 def f(x: a.X) -> None:
601 reveal_type(x)
602 x = a.X(1)
603 reveal_type(x)
604 [builtins fixtures/tuple.pyi]
605 [out]
606 tmp/b.py:4: note: Revealed type is "tuple[Any, fallback=a.X]"
607 tmp/b.py:6: note: Revealed type is "tuple[Any, fallback=a.X]"
608
609 [case testNamedTupleWithImportCycle2]
610 import a
611 [file a.py]
612 from collections import namedtuple
613 from b import f
614
615 N = namedtuple('N', 'a')
616 [file b.py]
617 import a
618
619 def f(x: a.N) -> None:
620 reveal_type(x)
621 if int():
622 x = a.N(1)
623 reveal_type(x)
624 [builtins fixtures/tuple.pyi]
625 [out]
626 tmp/b.py:4: note: Revealed type is "tuple[Any, fallback=a.N]"
627 tmp/b.py:7: note: Revealed type is "tuple[Any, fallback=a.N]"
628
629 [case testSimpleSelfReferentialNamedTuple]
630 from typing import NamedTuple
631
632 def test() -> None:
633 class MyNamedTuple(NamedTuple):
634 parent: 'MyNamedTuple' # E: Cannot resolve name "MyNamedTuple" (possible cyclic definition) \
635 # N: Recursive types are not allowed at function scope
636
637 def bar(nt: MyNamedTuple) -> MyNamedTuple:
638 return nt
639
640 x: MyNamedTuple
641 reveal_type(x.parent) # N: Revealed type is "Any"
642 [builtins fixtures/tuple.pyi]
643
644 -- Some crazy self-referential named tuples and types dicts
645 -- to be sure that everything works
646
647 [case testCrossFileNamedTupleForwardRefs]
648 import a
649 [file a.py]
650 import b
651 from typing import Any, NamedTuple
652
653 class A:
654 def a(self, b: 'b.B') -> str:
655 return 'a'
656 ATuple = NamedTuple('ATuple', [('a', Any)])
657
658 [file b.py]
659 import a
660
661 class B:
662 def b(self, a: 'a.A') -> str:
663 return 'b'
664 def aWithTuple(self, atuple: 'a.ATuple') -> str:
665 return 'a'
666 [builtins fixtures/tuple.pyi]
667 [out]
668
669 [case testSelfRefNT1]
670 from typing import Tuple, NamedTuple
671
672 def test() -> None:
673 Node = NamedTuple('Node', [
674 ('name', str),
675 ('children', Tuple['Node', ...]), # E: Cannot resolve name "Node" (possible cyclic definition) \
676 # N: Recursive types are not allowed at function scope
677 ])
678 n: Node
679 reveal_type(n) # N: Revealed type is "tuple[builtins.str, builtins.tuple[Any, ...], fallback=__main__.Node@4]"
680 [builtins fixtures/tuple.pyi]
681
682 [case testSelfRefNT2]
683 from typing import Tuple, NamedTuple
684
685 def test() -> None:
686 A = NamedTuple('A', [
687 ('x', str),
688 ('y', Tuple['B', ...]), # E: Cannot resolve name "B" (possible cyclic definition) \
689 # N: Recursive types are not allowed at function scope
690 ])
691 class B(NamedTuple):
692 x: A
693 y: int
694
695 n: A
696 reveal_type(n) # N: Revealed type is "tuple[builtins.str, builtins.tuple[Any, ...], fallback=__main__.A@4]"
697 [builtins fixtures/tuple.pyi]
698
699 [case testSelfRefNT3]
700 from typing import NamedTuple, Tuple
701
702 def test() -> None:
703 class B(NamedTuple):
704 x: Tuple[A, int] # E: Cannot resolve name "A" (possible cyclic definition) \
705 # N: Recursive types are not allowed at function scope
706 y: int
707
708 A = NamedTuple('A', [
709 ('x', str),
710 ('y', 'B'),
711 ])
712 n: B
713 m: A
714 reveal_type(n.x) # N: Revealed type is "tuple[Any, builtins.int]"
715 reveal_type(m[0]) # N: Revealed type is "builtins.str"
716 lst = [m, n]
717 reveal_type(lst[0]) # N: Revealed type is "tuple[builtins.object, builtins.object]"
718 [builtins fixtures/tuple.pyi]
719
720 [case testSelfRefNT4]
721 from typing import NamedTuple
722
723 def test() -> None:
724 class B(NamedTuple):
725 x: A # E: Cannot resolve name "A" (possible cyclic definition) \
726 # N: Recursive types are not allowed at function scope
727 y: int
728
729 class A(NamedTuple):
730 x: str
731 y: B
732
733 n: A
734 reveal_type(n.y[0]) # N: Revealed type is "Any"
735 [builtins fixtures/tuple.pyi]
736
737 [case testSelfRefNT5]
738 from typing import NamedTuple
739
740 def test() -> None:
741 B = NamedTuple('B', [
742 ('x', A), # E: Cannot resolve name "A" (possible cyclic definition) \
743 # N: Recursive types are not allowed at function scope \
744 # E: Name "A" is used before definition
745 ('y', int),
746 ])
747 A = NamedTuple('A', [
748 ('x', str),
749 ('y', 'B'),
750 ])
751 n: A
752 def f(m: B) -> None: pass
753 reveal_type(n) # N: Revealed type is "tuple[builtins.str, tuple[Any, builtins.int, fallback=__main__.B@4], fallback=__main__.A@8]"
754 reveal_type(f) # N: Revealed type is "def (m: tuple[Any, builtins.int, fallback=__main__.B@4])"
755 [builtins fixtures/tuple.pyi]
756
757 [case testRecursiveNamedTupleInBases]
758 from typing import List, NamedTuple, Union
759
760 def test() -> None:
761 Exp = Union['A', 'B'] # E: Cannot resolve name "Exp" (possible cyclic definition) \
762 # N: Recursive types are not allowed at function scope \
763 # E: Cannot resolve name "A" (possible cyclic definition)
764 class A(NamedTuple('A', [('attr', List[Exp])])): pass
765 class B(NamedTuple('B', [('val', object)])): pass
766
767 exp: Exp
768 reveal_type(exp) # N: Revealed type is "Any | tuple[builtins.object, fallback=__main__.B@6]"
769 if isinstance(exp, A):
770 reveal_type(exp[0][0]) # N: Revealed type is "Any | tuple[builtins.object, fallback=__main__.B@6]"
771 reveal_type(exp.attr[0]) # N: Revealed type is "Any | tuple[builtins.object, fallback=__main__.B@6]"
772 if isinstance(exp, B):
773 reveal_type(exp.val) # N: Revealed type is "builtins.object"
774 reveal_type(A([B(1), B(2)])) # N: Revealed type is "tuple[builtins.list[Any | tuple[builtins.object, fallback=__main__.B@6]], fallback=__main__.A@5]"
775 [builtins fixtures/isinstancelist.pyi]
776 [out]
777
778 [case testNamedTupleImportCycle]
779
780 import b
781 [file a.py]
782 class C:
783 pass
784
785 from b import tp
786 x: tp
787 reveal_type(x.x) # N: Revealed type is "builtins.int"
788
789 reveal_type(tp) # N: Revealed type is "def (x: builtins.int) -> tuple[builtins.int, fallback=b.tp]"
790 tp('x') # E: Argument 1 to "tp" has incompatible type "str"; expected "int"
791
792 [file b.py]
793 from a import C
794 from typing import NamedTuple
795
796 tp = NamedTuple('tp', [('x', int)])
797 [builtins fixtures/tuple.pyi]
798 [out]
799
800 [case testSubclassOfRecursiveNamedTuple]
801 from typing import List, NamedTuple
802
803 def test() -> None:
804 class Command(NamedTuple):
805 subcommands: List['Command'] # E: Cannot resolve name "Command" (possible cyclic definition) \
806 # N: Recursive types are not allowed at function scope
807
808 class HelpCommand(Command):
809 pass
810
811 hc = HelpCommand(subcommands=[])
812 reveal_type(hc) # N: Revealed type is "tuple[builtins.list[Any], fallback=__main__.HelpCommand@7]"
813 [builtins fixtures/list.pyi]
814 [out]
815
816 [case testUnsafeOverlappingNamedTuple]
817 from typing import NamedTuple
818
819 class Real(NamedTuple):
820 def __sub__(self, other: Real) -> str: return ""
821 class Fraction(Real):
822 def __rsub__(self, other: Real) -> Real: return other # E: Signatures of "__rsub__" of "Fraction" and "__sub__" of "Real" are unsafely overlapping
823 [builtins fixtures/tuple.pyi]
824
825 [case testForwardReferenceInNamedTuple]
826 from typing import NamedTuple
827
828 class A(NamedTuple):
829 b: 'B'
830 x: int
831
832 class B:
833 pass
834 [builtins fixtures/tuple.pyi]
835
836 [case testTypeNamedTupleClassmethod]
837 from typing import Type, NamedTuple
838 class D(NamedTuple):
839 @classmethod
840 def f(cls) -> None: pass
841
842 d: Type[D]
843 d.g() # E: "type[D]" has no attribute "g"
844 d.f()
845 [builtins fixtures/classmethod.pyi]
846
847 [case testTypeNamedTupleCall]
848
849 from typing import NamedTuple
850
851 Thing = NamedTuple('Thing', [('s', str), ('n', int)])
852
853 class CallableTuple(Thing):
854 def __call__(self) -> None:
855 pass
856
857 o = CallableTuple('hello ', 12)
858 o()
859 [builtins fixtures/tuple.pyi]
860
861 [case testNamedTupleSubclassMulti]
862 from typing import NamedTuple
863
864 class Base:
865 pass
866 class BaseTuple(NamedTuple):
867 value: float
868 class MyTuple(BaseTuple, Base):
869 pass
870
871 def f(o: Base) -> None:
872 if isinstance(o, MyTuple):
873 reveal_type(o.value) # N: Revealed type is "builtins.float"
874 [builtins fixtures/isinstance.pyi]
875 [out]
876
877 [case testNamedTupleNew]
878 from typing import NamedTuple
879
880 Base = NamedTuple('Base', [('param', int)])
881
882 class Child(Base):
883 def __new__(cls, param: int = 1) -> 'Child':
884 return Base.__new__(cls, param)
885
886 Base(param=10)
887 Child(param=10)
888 [builtins fixtures/tuple.pyi]
889
890 [case testNamedTupleClassMethodWithGenericReturnValue]
891 from typing import TypeVar, Type, NamedTuple
892
893 T = TypeVar('T', bound='Parent')
894
895 class Parent(NamedTuple):
896 x: str
897
898 @classmethod
899 def class_method(cls: Type[T]) -> T:
900 return cls(x='text')
901
902 class Child(Parent):
903 pass
904
905 reveal_type(Child.class_method()) # N: Revealed type is "tuple[builtins.str, fallback=__main__.Child]"
906 [builtins fixtures/classmethod.pyi]
907
908 [case testNamedTupleAsConditionalStrictOptionalDisabled]
909 # flags: --no-strict-optional --warn-unreachable
910 from typing import NamedTuple
911
912 class C(NamedTuple):
913 a: int
914 b: str
915
916 a: C
917 if not a:
918 1() # E: "int" not callable
919 b = (1, 2)
920 if not b:
921 ''() # E: "str" not callable
922 [builtins fixtures/tuple.pyi]
923
924 [case testNamedTupleDoubleForward]
925 # flags: --disable-error-code=used-before-def
926 from typing import Union, Mapping, NamedTuple
927
928 class MyBaseTuple(NamedTuple):
929 base_field_1: int
930 base_field_2: int
931
932 MyBaseTupleMapping = Mapping[MyBaseTuple, int]
933 MyTupleUnion = Union[MyTupleA, MyTupleB]
934
935 class MyTupleA(NamedTuple):
936 field_1: MyBaseTupleMapping
937 field_2: MyBaseTuple
938
939
940 class MyTupleB(NamedTuple):
941 field_1: MyBaseTupleMapping
942 field_2: MyBaseTuple
943
944 u: MyTupleUnion
945 reveal_type(u.field_1) # N: Revealed type is "typing.Mapping[tuple[builtins.int, builtins.int, fallback=__main__.MyBaseTuple], builtins.int]"
946 reveal_type(u.field_2) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.MyBaseTuple]"
947 reveal_type(u[0]) # N: Revealed type is "typing.Mapping[tuple[builtins.int, builtins.int, fallback=__main__.MyBaseTuple], builtins.int]"
948 reveal_type(u[1]) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.MyBaseTuple]"
949 [builtins fixtures/tuple.pyi]
950
951 [case testAssignNamedTupleAsAttribute]
952 from typing import NamedTuple
953
954 class A:
955 def __init__(self) -> None:
956 self.b = NamedTuple('x', [('s', str), ('n', int)]) # E: NamedTuple type as an attribute is not supported
957
958 reveal_type(A().b) # N: Revealed type is "typing.NamedTuple"
959 [builtins fixtures/tuple.pyi]
960 [typing fixtures/typing-namedtuple.pyi]
961
962
963 [case testEmptyNamedTupleTypeRepr]
964 from typing import NamedTuple
965
966 N = NamedTuple('N', [])
967 n: N
968 reveal_type(N) # N: Revealed type is "def () -> tuple[(), fallback=__main__.N]"
969 reveal_type(n) # N: Revealed type is "tuple[(), fallback=__main__.N]"
970 [builtins fixtures/tuple.pyi]
971
972 [case testNamedTupleWrongfile]
973 from typing import NamedTuple
974 from b import Type1
975 Type2 = NamedTuple('Type2', [('x', Type1)])
976 [file b.py]
977 from typing import NamedTuple
978
979 def foo():
980 pass
981
982 Type1 = NamedTuple('Type1', [('foo', foo)]) # E: Function "b.foo" is not valid as a type # N: Perhaps you need "Callable[...]" or a callback protocol?
983
984 [builtins fixtures/tuple.pyi]
985
986 [case testNamedTupleTypeNameMatchesVariableName]
987 from typing import NamedTuple
988 from collections import namedtuple
989
990 A = NamedTuple('X', [('a', int)]) # E: First argument to namedtuple() should be "A", not "X"
991 B = namedtuple('X', ['a']) # E: First argument to namedtuple() should be "B", not "X"
992
993 C = NamedTuple('X', [('a', 'Y')]) # E: First argument to namedtuple() should be "C", not "X"
994 class Y: ...
995 [builtins fixtures/tuple.pyi]
996
997 [case testNamedTupleTypeIsASuperTypeOfOtherNamedTuples]
998 from typing import Tuple, NamedTuple
999
1000 class Bar(NamedTuple):
1001 name: str = "Bar"
1002
1003 class Baz(NamedTuple):
1004 a: str
1005 b: str
1006
1007 class Biz(Baz): ...
1008 class Other: ...
1009 class Both1(Bar, Other): ...
1010 class Both2(Other, Bar): ...
1011 class Both3(Biz, Other): ...
1012
1013 def print_namedtuple(obj: NamedTuple) -> None:
1014 reveal_type(obj._fields) # N: Revealed type is "builtins.tuple[builtins.str, ...]"
1015
1016 b1: Bar
1017 b2: Baz
1018 b3: Biz
1019 b4: Both1
1020 b5: Both2
1021 b6: Both3
1022 print_namedtuple(b1) # ok
1023 print_namedtuple(b2) # ok
1024 print_namedtuple(b3) # ok
1025 print_namedtuple(b4) # ok
1026 print_namedtuple(b5) # ok
1027 print_namedtuple(b6) # ok
1028
1029 print_namedtuple(1) # E: Argument 1 to "print_namedtuple" has incompatible type "int"; expected "NamedTuple"
1030 print_namedtuple(('bar',)) # E: Argument 1 to "print_namedtuple" has incompatible type "tuple[str]"; expected "NamedTuple"
1031 print_namedtuple((1, 2)) # E: Argument 1 to "print_namedtuple" has incompatible type "tuple[int, int]"; expected "NamedTuple"
1032 print_namedtuple((b1,)) # E: Argument 1 to "print_namedtuple" has incompatible type "tuple[Bar]"; expected "NamedTuple"
1033 t: Tuple[str, ...]
1034 print_namedtuple(t) # E: Argument 1 to "print_namedtuple" has incompatible type "tuple[str, ...]"; expected "NamedTuple"
1035
1036 [builtins fixtures/tuple.pyi]
1037 [typing fixtures/typing-namedtuple.pyi]
1038
1039 [case testNamedTupleTypeIsASuperTypeOfOtherNamedTuplesReturns]
1040 from typing import Tuple, NamedTuple
1041
1042 class Bar(NamedTuple):
1043 n: int
1044
1045 class Baz(NamedTuple):
1046 a: str
1047 b: str
1048
1049 class Biz(Bar): ...
1050 class Other: ...
1051 class Both1(Bar, Other): ...
1052 class Both2(Other, Bar): ...
1053 class Both3(Biz, Other): ...
1054
1055 def good1() -> NamedTuple:
1056 b: Bar
1057 return b
1058 def good2() -> NamedTuple:
1059 b: Baz
1060 return b
1061 def good3() -> NamedTuple:
1062 b: Biz
1063 return b
1064 def good4() -> NamedTuple:
1065 b: Both1
1066 return b
1067 def good5() -> NamedTuple:
1068 b: Both2
1069 return b
1070 def good6() -> NamedTuple:
1071 b: Both3
1072 return b
1073
1074 def bad1() -> NamedTuple:
1075 return 1 # E: Incompatible return value type (got "int", expected "NamedTuple")
1076 def bad2() -> NamedTuple:
1077 return () # E: Incompatible return value type (got "tuple[()]", expected "NamedTuple")
1078 def bad3() -> NamedTuple:
1079 return (1, 2) # E: Incompatible return value type (got "tuple[int, int]", expected "NamedTuple")
1080
1081 [builtins fixtures/tuple.pyi]
1082 [typing fixtures/typing-namedtuple.pyi]
1083
1084 [case testBoolInTuplesRegression]
1085 # https://github.com/python/mypy/issues/11701
1086 from typing import NamedTuple, Literal, List, Tuple
1087
1088 C = NamedTuple("C", [("x", Literal[True, False])])
1089
1090 T = Tuple[Literal[True, False]]
1091
1092 # Was error here:
1093 # Incompatible types in assignment (expression has type "list[C]", variable has type "list[C]")
1094 x: List[C] = [C(True)]
1095
1096 t: T
1097
1098 # Was error here:
1099 # Incompatible types in assignment (expression has type "list[tuple[bool]]",
1100 # variable has type "list[tuple[Union[Literal[True], Literal[False]]]]")
1101 y: List[T] = [t]
1102 [builtins fixtures/tuple.pyi]
1103 [typing fixtures/typing-namedtuple.pyi]
1104
1105 [case testNamedTupleWithBoolNarrowsToBool]
1106 # flags: --warn-unreachable
1107 from typing import NamedTuple
1108
1109 class C(NamedTuple):
1110 x: int
1111
1112 def __bool__(self) -> bool:
1113 pass
1114
1115 def foo(c: C) -> None:
1116 if c:
1117 reveal_type(c) # N: Revealed type is "tuple[builtins.int, fallback=__main__.C]"
1118 else:
1119 reveal_type(c) # N: Revealed type is "tuple[builtins.int, fallback=__main__.C]"
1120
1121 def bar(c: C) -> None:
1122 if not c:
1123 reveal_type(c) # N: Revealed type is "tuple[builtins.int, fallback=__main__.C]"
1124 else:
1125 reveal_type(c) # N: Revealed type is "tuple[builtins.int, fallback=__main__.C]"
1126
1127 class C1(NamedTuple):
1128 x: int
1129
1130 def foo1(c: C1) -> None:
1131 if c:
1132 reveal_type(c) # N: Revealed type is "tuple[builtins.int, fallback=__main__.C1]"
1133 else:
1134 c # E: Statement is unreachable
1135
1136 def bar1(c: C1) -> None:
1137 if not c:
1138 c # E: Statement is unreachable
1139 else:
1140 reveal_type(c) # N: Revealed type is "tuple[builtins.int, fallback=__main__.C1]"
1141 [builtins fixtures/tuple.pyi]
1142 [typing fixtures/typing-namedtuple.pyi]
1143
1144 [case testInvalidNamedTupleWithinFunction]
1145 from collections import namedtuple
1146
1147 def f(fields) -> None:
1148 TupleType = namedtuple("TupleType", fields) \
1149 # E: List or tuple literal expected as the second argument to "namedtuple()"
1150 class InheritFromTuple(TupleType):
1151 pass
1152 t: TupleType
1153 it: InheritFromTuple
1154 NT2 = namedtuple("bad", "x") # E: First argument to namedtuple() should be "NT2", not "bad"
1155 nt2: NT2 = NT2(x=1)
1156 [builtins fixtures/tuple.pyi]
1157
1158 [case testNamedTupleHasMatchArgs]
1159 from typing import NamedTuple
1160 class One(NamedTuple):
1161 bar: int
1162 baz: str
1163 o: One
1164 reveal_type(o.__match_args__) # N: Revealed type is "tuple[Literal['bar'], Literal['baz']]"
1165 [builtins fixtures/tuple.pyi]
1166 [typing fixtures/typing-namedtuple.pyi]
1167
1168 [case testNamedTupleNoBytes]
1169 from collections import namedtuple
1170 from typing import NamedTuple
1171
1172 NT1 = namedtuple('NT1', b'x y z') # E: List or tuple literal expected as the second argument to "namedtuple()"
1173 NT2 = namedtuple(b'NT2', 'x y z') # E: "namedtuple()" expects a string literal as the first argument \
1174 # E: Argument 1 to "namedtuple" has incompatible type "bytes"; expected "str"
1175 NT3 = namedtuple('NT3', [b'x', 'y']) # E: String literal expected as "namedtuple()" item
1176
1177 NT4 = NamedTuple('NT4', [('x', int), (b'y', int)]) # E: Invalid "NamedTuple()" field name
1178 NT5 = NamedTuple(b'NT5', [('x', int), ('y', int)]) # E: "NamedTuple()" expects a string literal as the first argument
1179
1180 [builtins fixtures/tuple.pyi]
1181 [typing fixtures/typing-namedtuple.pyi]
1182
1183 [case testGenericNamedTupleCreation]
1184 from typing import Generic, NamedTuple, TypeVar
1185
1186 T = TypeVar("T")
1187 class NT(NamedTuple, Generic[T]):
1188 key: int
1189 value: T
1190
1191 nts: NT[str]
1192 reveal_type(nts) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=__main__.NT[builtins.str]]"
1193 reveal_type(nts.value) # N: Revealed type is "builtins.str"
1194
1195 nti = NT(key=0, value=0)
1196 reveal_type(nti) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.NT[builtins.int]]"
1197 reveal_type(nti.value) # N: Revealed type is "builtins.int"
1198
1199 NT[str](key=0, value=0) # E: Argument "value" to "NT" has incompatible type "int"; expected "str"
1200 [builtins fixtures/tuple.pyi]
1201 [typing fixtures/typing-namedtuple.pyi]
1202
1203 [case testGenericNamedTupleAlias]
1204 from typing import NamedTuple, Generic, TypeVar, List
1205
1206 T = TypeVar("T")
1207 class NT(NamedTuple, Generic[T]):
1208 key: int
1209 value: T
1210
1211 Alias = NT[List[T]]
1212
1213 an: Alias[str]
1214 reveal_type(an) # N: Revealed type is "tuple[builtins.int, builtins.list[builtins.str], fallback=__main__.NT[builtins.list[builtins.str]]]"
1215 Alias[str](key=0, value=0) # E: Argument "value" to "NT" has incompatible type "int"; expected "list[str]"
1216 [builtins fixtures/tuple.pyi]
1217 [typing fixtures/typing-namedtuple.pyi]
1218
1219 [case testGenericNamedTupleMethods]
1220 from typing import Generic, NamedTuple, TypeVar
1221
1222 T = TypeVar("T")
1223 class NT(NamedTuple, Generic[T]):
1224 key: int
1225 value: T
1226 x: int
1227
1228 nti: NT[int]
1229 reveal_type(nti * x) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
1230
1231 nts: NT[str]
1232 reveal_type(nts * x) # N: Revealed type is "builtins.tuple[builtins.int | builtins.str, ...]"
1233 [builtins fixtures/tuple.pyi]
1234 [typing fixtures/typing-namedtuple.pyi]
1235
1236 [case testGenericNamedTupleCustomMethods]
1237 from typing import Generic, NamedTuple, TypeVar
1238
1239 T = TypeVar("T")
1240 class NT(NamedTuple, Generic[T]):
1241 key: int
1242 value: T
1243 def foo(self) -> T: ...
1244 @classmethod
1245 def from_value(cls, value: T) -> NT[T]: ...
1246
1247 nts: NT[str]
1248 reveal_type(nts.foo()) # N: Revealed type is "builtins.str"
1249
1250 nti = NT.from_value(1)
1251 reveal_type(nti) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.NT[builtins.int]]"
1252 NT[str].from_value(1) # E: Argument 1 to "from_value" of "NT" has incompatible type "int"; expected "str"
1253 [builtins fixtures/tuple.pyi]
1254 [typing fixtures/typing-namedtuple.pyi]
1255
1256 [case testGenericNamedTupleSubtyping]
1257 from typing import Generic, NamedTuple, TypeVar, Tuple
1258
1259 T = TypeVar("T")
1260 class NT(NamedTuple, Generic[T]):
1261 key: int
1262 value: T
1263
1264 nts: NT[str]
1265 nti: NT[int]
1266
1267 def foo(x: Tuple[int, ...]) -> None: ...
1268 foo(nti)
1269 foo(nts) # E: Argument 1 to "foo" has incompatible type "NT[str]"; expected "tuple[int, ...]"
1270 [builtins fixtures/tuple.pyi]
1271 [typing fixtures/typing-namedtuple.pyi]
1272
1273 [case testGenericNamedTupleJoin]
1274 from typing import Generic, NamedTuple, TypeVar, Tuple
1275
1276 T = TypeVar("T", covariant=True)
1277 class NT(NamedTuple, Generic[T]):
1278 key: int
1279 value: T
1280
1281 nts: NT[str]
1282 nti: NT[int]
1283 x: Tuple[int, ...]
1284
1285 S = TypeVar("S")
1286 def foo(x: S, y: S) -> S: ...
1287 reveal_type(foo(nti, nti)) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.NT[builtins.int]]"
1288
1289 reveal_type(foo(nti, nts)) # N: Revealed type is "tuple[builtins.int, builtins.object, fallback=__main__.NT[builtins.object]]"
1290 reveal_type(foo(nts, nti)) # N: Revealed type is "tuple[builtins.int, builtins.object, fallback=__main__.NT[builtins.object]]"
1291
1292 reveal_type(foo(nti, x)) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
1293 reveal_type(foo(nts, x)) # N: Revealed type is "builtins.tuple[builtins.int | builtins.str, ...]"
1294 reveal_type(foo(x, nti)) # N: Revealed type is "builtins.tuple[builtins.int, ...]"
1295 reveal_type(foo(x, nts)) # N: Revealed type is "builtins.tuple[builtins.int | builtins.str, ...]"
1296 [builtins fixtures/tuple.pyi]
1297 [typing fixtures/typing-namedtuple.pyi]
1298
1299 [case testGenericNamedTupleCallSyntax]
1300 from typing import NamedTuple, TypeVar
1301
1302 T = TypeVar("T")
1303 NT = NamedTuple("NT", [("key", int), ("value", T)])
1304 reveal_type(NT) # N: Revealed type is "def [T] (key: builtins.int, value: T`1) -> tuple[builtins.int, T`1, fallback=__main__.NT[T`1]]"
1305
1306 nts: NT[str]
1307 reveal_type(nts) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=__main__.NT[builtins.str]]"
1308
1309 nti = NT(key=0, value=0)
1310 reveal_type(nti) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.NT[builtins.int]]"
1311 NT[str](key=0, value=0) # E: Argument "value" to "NT" has incompatible type "int"; expected "str"
1312 [builtins fixtures/tuple.pyi]
1313 [typing fixtures/typing-namedtuple.pyi]
1314
1315 [case testGenericNamedTupleNoLegacySyntax]
1316 from typing import TypeVar, NamedTuple
1317
1318 T = TypeVar("T")
1319 class C(
1320 NamedTuple("_C", [("x", int), ("y", T)]) # E: Generic named tuples are not supported for legacy class syntax \
1321 # N: Use either Python 3 class syntax, or the assignment syntax
1322 ): ...
1323
1324 [builtins fixtures/tuple.pyi]
1325 [typing fixtures/typing-namedtuple.pyi]
1326
1327 [case testNamedTupleSelfItemNotAllowed]
1328 from typing import Self, NamedTuple, Optional
1329
1330 class NT(NamedTuple):
1331 val: int
1332 next: Optional[Self] # E: Self type cannot be used in NamedTuple item type
1333 NTC = NamedTuple("NTC", [("val", int), ("next", Optional[Self])]) # E: Self type cannot be used in NamedTuple item type
1334 [builtins fixtures/tuple.pyi]
1335 [typing fixtures/typing-namedtuple.pyi]
1336
1337 [case testNamedTupleTypingSelfMethod]
1338 from typing import Self, NamedTuple, TypeVar, Generic
1339
1340 T = TypeVar("T")
1341 class NT(NamedTuple, Generic[T]):
1342 key: str
1343 val: T
1344 def meth(self) -> Self:
1345 nt: NT[int]
1346 if bool():
1347 return nt._replace() # E: Incompatible return value type (got "NT[int]", expected "Self")
1348 else:
1349 return self._replace()
1350
1351 class SNT(NT[int]): ...
1352 reveal_type(SNT("test", 42).meth()) # N: Revealed type is "tuple[builtins.str, builtins.int, fallback=__main__.SNT]"
1353 [builtins fixtures/tuple.pyi]
1354 [typing fixtures/typing-namedtuple.pyi]
1355
1356 [case testNoCrashUnsupportedNamedTuple]
1357 from typing import NamedTuple
1358 class Test:
1359 def __init__(self, field) -> None:
1360 self.Item = NamedTuple("x", [(field, str)]) # E: NamedTuple type as an attribute is not supported
1361 self.item: self.Item # E: Name "self.Item" is not defined
1362 [builtins fixtures/tuple.pyi]
1363 [typing fixtures/typing-namedtuple.pyi]
1364
1365 [case testNoClassKeywordsForNamedTuple_no_native_parse]
1366 from typing import NamedTuple
1367 class Test1(NamedTuple, x=1, y=2): # E: Unexpected keyword argument "x" for "__init_subclass__" of "NamedTuple" \
1368 # E: Unexpected keyword argument "y" for "__init_subclass__" of "NamedTuple"
1369 ...
1370
1371 class Meta(type): ...
1372
1373 class Test2(NamedTuple, metaclass=Meta): # E: Unexpected keyword argument "metaclass" for "__init_subclass__" of "NamedTuple"
1374 ...
1375
1376 # Technically this would work, but it is just easier for the implementation:
1377 class Test3(NamedTuple, metaclass=type): # E: Unexpected keyword argument "metaclass" for "__init_subclass__" of "NamedTuple"
1378 ...
1379 [builtins fixtures/tuple.pyi]
1380 [typing fixtures/typing-namedtuple.pyi]
1381
1382
1383 [case testNamedTupleDunderReplace]
1384 # flags: --python-version 3.13
1385 from typing import NamedTuple
1386
1387 class A(NamedTuple):
1388 x: int
1389
1390 A(x=0).__replace__(x=1)
1391 A(x=0).__replace__(x="asdf") # E: Argument "x" to "__replace__" of "A" has incompatible type "str"; expected "int"
1392 A(x=0).__replace__(y=1) # E: Unexpected keyword argument "y" for "__replace__" of "A"
1393 [builtins fixtures/tuple.pyi]
1394 [typing fixtures/typing-namedtuple.pyi]
1395
1396 [case testUnpackSelfNamedTuple]
1397 import typing
1398
1399 class Foo(typing.NamedTuple):
1400 bar: int
1401 def baz(self: typing.Self) -> None:
1402 x, = self
1403 reveal_type(x) # N: Revealed type is "builtins.int"
1404 [builtins fixtures/tuple.pyi]
1405 [typing fixtures/typing-namedtuple.pyi]
1406
1407 [case testNameErrorInNamedTupleNestedInFunction1]
1408 from typing import NamedTuple
1409
1410 def bar() -> None:
1411 class MyNamedTuple(NamedTuple):
1412 a: int
1413 def foo(self) -> None:
1414 ...
1415 int_set: Set[int] # E: Name "Set" is not defined \
1416 # N: Did you forget to import it from "typing"? (Suggestion: "from typing import Set")
1417 [builtins fixtures/tuple.pyi]
1418 [typing fixtures/typing-namedtuple.pyi]
1419
1420 [case testNameErrorInNamedTupleNestedInFunction2]
1421 from typing import NamedTuple
1422
1423 def bar() -> None:
1424 class MyNamedTuple(NamedTuple):
1425 a: int
1426 def foo(self) -> None:
1427 misspelled_var_name # E: Name "misspelled_var_name" is not defined
1428 [builtins fixtures/tuple.pyi]
1429 [typing fixtures/typing-namedtuple.pyi]
1430
1431
1432 [case testNamedTupleFinalAndClassVar]
1433 from typing import NamedTuple, Final, ClassVar
1434
1435 class My(NamedTuple):
1436 a: Final # E: Final[...] can't be used inside a NamedTuple
1437 b: Final[int] # E: Final[...] can't be used inside a NamedTuple
1438 c: ClassVar # E: ClassVar[...] can't be used inside a NamedTuple
1439 d: ClassVar[int] # E: ClassVar[...] can't be used inside a NamedTuple
1440
1441 Func = NamedTuple('Func', [
1442 ('a', Final), # E: Final[...] can't be used inside a NamedTuple
1443 ('b', Final[int]), # E: Final[...] can't be used inside a NamedTuple
1444 ('c', ClassVar), # E: ClassVar[...] can't be used inside a NamedTuple
1445 ('d', ClassVar[int]), # E: ClassVar[...] can't be used inside a NamedTuple
1446 ])
1447 [builtins fixtures/tuple.pyi]
1448 [typing fixtures/typing-namedtuple.pyi]
1449
1450 [case testGenericNamedTupleRecursiveBound]
1451 from typing import Generic, NamedTuple, TypeVar
1452 T = TypeVar("T", bound="NT")
1453 class NT(NamedTuple, Generic[T]):
1454 parent: T
1455 item: int
1456
1457 def main(n: NT[T]) -> None:
1458 reveal_type(n.parent) # N: Revealed type is "T`-1"
1459 reveal_type(n.item) # N: Revealed type is "builtins.int"
1460
1461 [builtins fixtures/tuple.pyi]
1462 [typing fixtures/typing-namedtuple.pyi]
1463
1464 [case testNamedTupleOverlappingCheck]
1465 from typing import overload, NamedTuple, Union
1466
1467 class AKey(NamedTuple):
1468 k: str
1469
1470 class A(NamedTuple):
1471 key: AKey
1472
1473
1474 class BKey(NamedTuple):
1475 k: str
1476
1477 class B(NamedTuple):
1478 key: BKey
1479
1480 @overload
1481 def f(arg: A) -> A: ...
1482 @overload
1483 def f(arg: B) -> B: ...
1484 def f(arg: Union[A, B]) -> Union[A, B]: ...
1485
1486 def g(x: Union[A, B, str]) -> Union[A, B, str]:
1487 if isinstance(x, str):
1488 return x
1489 else:
1490 reveal_type(x) # N: Revealed type is "tuple[tuple[builtins.str, fallback=__main__.AKey], fallback=__main__.A] | tuple[tuple[builtins.str, fallback=__main__.BKey], fallback=__main__.B]"
1491 return x._replace()
1492
1493 # no errors should be raised above.
1494 [builtins fixtures/tuple.pyi]
1495
1496 [case testNamedTupleUnionAnyMethodCall]
1497 from collections import namedtuple
1498 from typing import Any, Union
1499
1500 T = namedtuple("T", ["x"])
1501
1502 class C(T):
1503 def f(self) -> bool:
1504 return True
1505
1506 c: Union[C, Any]
1507 reveal_type(c.f()) # N: Revealed type is "builtins.bool | Any"
1508 [builtins fixtures/tuple.pyi]
1509
1510 [case testNamedTupleAsClassMemberNoCrash]
1511 # https://github.com/python/mypy/issues/18736
1512 from collections import namedtuple
1513
1514 class Base:
1515 def __init__(self, namespace: tuple[str, ...]) -> None:
1516 # Not a bug: trigger defer
1517 names = [name for name in namespace if fail] # E: Name "fail" is not defined
1518 self.n = namedtuple("n", names) # E: NamedTuple type as an attribute is not supported
1519 [builtins fixtures/tuple.pyi]
1520
1521 [case testNamedTupleDefaultValueDefer]
1522 # flags: --debug-serialize
1523 from typing import NamedTuple
1524
1525 class NT(NamedTuple):
1526 foo: int = UNDEFINED # E: Name "UNDEFINED" is not defined
1527 [builtins fixtures/tuple.pyi]
1528
1529 [case testNamedTupleDefaultValueDefer2]
1530 # flags: --debug-serialize
1531 from typing import NamedTuple
1532
1533 class NT(NamedTuple):
1534 foo: int = DEFERRED_INT
1535
1536 class NT2(NamedTuple):
1537 foo: int = DEFERRED_STR # E: Incompatible types in assignment (expression has type "str", variable has type "int")
1538
1539 from foo import DEFERRED_INT, DEFERRED_STR
1540
1541 [file foo.py]
1542 DEFERRED_INT = 1
1543 DEFERRED_STR = "a"
1544 [builtins fixtures/tuple.pyi]