Debian Codegraph @

test-data/unit/check-class-namedtuple.test

raw
1 [case testNewNamedTupleNoUnderscoreFields]
2 from typing import NamedTuple
3
4 class X(NamedTuple):
5 x: int
6 _y: int # E: NamedTuple field name cannot start with an underscore: _y
7 _z: int # E: NamedTuple field name cannot start with an underscore: _z
8 [builtins fixtures/tuple.pyi]
9
10 [case testNewNamedTupleAccessingAttributes]
11 from typing import NamedTuple
12
13 class X(NamedTuple):
14 x: int
15 y: str
16
17 x: X
18 x.x
19 x.y
20 x.z # E: "X" has no attribute "z"
21 [builtins fixtures/tuple.pyi]
22
23 [case testNewNamedTupleAttributesAreReadOnly]
24 from typing import NamedTuple
25
26 class X(NamedTuple):
27 x: int
28
29 x: X
30 x.x = 5 # E: Property "x" defined in "X" is read-only
31 x.y = 5 # E: "X" has no attribute "y"
32
33 class A(X): pass
34 a: A
35 a.x = 5 # E: Property "x" defined in "X" is read-only
36 [builtins fixtures/tuple.pyi]
37
38 [case testNewNamedTupleCreateWithPositionalArguments]
39 from typing import NamedTuple
40
41 class X(NamedTuple):
42 x: int
43 y: str
44
45 x = X(1, '2')
46 x.x
47 x.z # E: "X" has no attribute "z"
48 x = X(1) # E: Missing positional argument "y" in call to "X"
49 x = X(1, '2', 3) # E: Too many arguments for "X"
50 [builtins fixtures/tuple.pyi]
51
52 [case testNewNamedTupleShouldBeSingleBase]
53 from typing import NamedTuple
54
55 class A: ...
56 class X(NamedTuple, A): # E: NamedTuple should be a single base
57 pass
58 [builtins fixtures/tuple.pyi]
59
60 [case testCreateNewNamedTupleWithKeywordArguments]
61 from typing import NamedTuple
62
63 class X(NamedTuple):
64 x: int
65 y: str
66
67 x = X(x=1, y='x')
68 x = X(1, y='x')
69 x = X(x=1, z=1) # E: Unexpected keyword argument "z" for "X"
70 x = X(y='x') # E: Missing positional argument "x" in call to "X"
71 [builtins fixtures/tuple.pyi]
72
73 [case testNewNamedTupleCreateAndUseAsTuple]
74 from typing import NamedTuple
75
76 class X(NamedTuple):
77 x: int
78 y: str
79
80 x = X(1, 'x')
81 a, b = x
82 a, b, c = x # E: Need more than 2 values to unpack (3 expected)
83 [builtins fixtures/tuple.pyi]
84
85 [case testNewNamedTupleWithItemTypes]
86 from typing import NamedTuple
87
88 class N(NamedTuple):
89 a: int
90 b: str
91
92 n = N(1, 'x')
93 s: str = n.a # E: Incompatible types in assignment (expression has type "int", \
94 variable has type "str")
95 i: int = n.b # E: Incompatible types in assignment (expression has type "str", \
96 variable has type "int")
97 x, y = n
98 if int():
99 x = y # E: Incompatible types in assignment (expression has type "str", variable has type "int")
100 [builtins fixtures/tuple.pyi]
101
102 [case testNewNamedTupleConstructorArgumentTypes]
103 from typing import NamedTuple
104
105 class N(NamedTuple):
106 a: int
107 b: str
108
109 n = N('x', 'x') # E: Argument 1 to "N" has incompatible type "str"; expected "int"
110 n = N(1, b=2) # E: Argument "b" to "N" has incompatible type "int"; expected "str"
111 N(1, 'x')
112 N(b='x', a=1)
113 [builtins fixtures/tuple.pyi]
114
115 [case testNewNamedTupleAsBaseClass]
116 from typing import NamedTuple
117
118 class N(NamedTuple):
119 a: int
120 b: str
121
122 class X(N):
123 pass
124 x = X(1, 2) # E: Argument 2 to "X" has incompatible type "int"; expected "str"
125 s = ''
126 i = 0
127 if int():
128 s = x.a # E: Incompatible types in assignment (expression has type "int", variable has type "str")
129 if int():
130 i, s = x
131 if int():
132 s, s = x # E: Incompatible types in assignment (expression has type "int", variable has type "str")
133 [builtins fixtures/tuple.pyi]
134
135 [case testNewNamedTupleSelfTypeWithNamedTupleAsBase]
136 from typing import NamedTuple
137
138 class A(NamedTuple):
139 a: int
140 b: str
141
142 class B(A):
143 def f(self, x: int) -> None:
144 self.f(self.a)
145 self.f(self.b) # E: Argument 1 to "f" of "B" has incompatible type "str"; expected "int"
146 i = 0
147 s = ''
148 if int():
149 i, s = self
150 i, i = self # E: Incompatible types in assignment (expression has type "str", \
151 variable has type "int")
152 [builtins fixtures/tuple.pyi]
153 [out]
154
155 [case testNewNamedTupleTypeReferenceToClassDerivedFrom]
156 from typing import NamedTuple
157
158 class A(NamedTuple):
159 a: int
160 b: str
161
162 class B(A):
163 def f(self, x: 'B') -> None:
164 i = 0
165 s = ''
166 if int():
167 self = x
168 i, s = x
169 i, s = x.a, x.b
170 i, s = x.a, x.a # E: Incompatible types in assignment (expression has type "int", \
171 variable has type "str")
172 i, i = self # E: Incompatible types in assignment (expression has type "str", \
173 variable has type "int")
174 [builtins fixtures/tuple.pyi]
175
176 [case testNewNamedTupleSubtyping]
177 from typing import NamedTuple, Tuple
178
179 class A(NamedTuple):
180 a: int
181 b: str
182
183 class B(A): pass
184 a = A(1, '')
185 b = B(1, '')
186 t: Tuple[int, str]
187 if int():
188 b = a # E: Incompatible types in assignment (expression has type "A", variable has type "B")
189 if int():
190 a = t # E: Incompatible types in assignment (expression has type "tuple[int, str]", variable has type "A")
191 if int():
192 b = t # E: Incompatible types in assignment (expression has type "tuple[int, str]", variable has type "B")
193 if int():
194 t = a
195 if int():
196 t = (1, '')
197 if int():
198 t = b
199 if int():
200 a = b
201 [builtins fixtures/tuple.pyi]
202
203 [case testNewNamedTupleSimpleTypeInference]
204 from typing import NamedTuple, Tuple
205
206 class A(NamedTuple):
207 a: int
208
209 l = [A(1), A(2)]
210 a = A(1)
211 a = l[0]
212 (i,) = l[0]
213 i, i = l[0] # E: Need more than 1 value to unpack (2 expected)
214 l = [A(1)]
215 a = (1,) # E: Incompatible types in assignment (expression has type "tuple[int]", \
216 variable has type "A")
217 [builtins fixtures/list.pyi]
218
219 [case testNewNamedTupleMissingClassAttribute]
220 from typing import NamedTuple
221
222 class MyNamedTuple(NamedTuple):
223 a: int
224 b: str
225
226 MyNamedTuple.x # E: "type[MyNamedTuple]" has no attribute "x"
227 [builtins fixtures/tuple.pyi]
228
229 [case testNewNamedTupleEmptyItems]
230 from typing import NamedTuple
231
232 class A(NamedTuple):
233 ...
234 [builtins fixtures/tuple.pyi]
235
236 [case testNewNamedTupleForwardRef]
237 from typing import NamedTuple
238
239 class A(NamedTuple):
240 b: 'B'
241
242 class B: ...
243
244 a = A(B())
245 a = A(1) # E: Argument 1 to "A" has incompatible type "int"; expected "B"
246 [builtins fixtures/tuple.pyi]
247
248 [case testNewNamedTupleProperty36]
249 from typing import NamedTuple
250
251 class A(NamedTuple):
252 a: int
253
254 class B(A):
255 @property
256 def b(self) -> int:
257 return self.a
258 class C(B): pass
259 B(1).b
260 C(2).b
261
262 [builtins fixtures/property.pyi]
263
264 [case testNewNamedTupleAsDict]
265 from typing import NamedTuple, Any
266
267 class X(NamedTuple):
268 x: Any
269 y: Any
270
271 x: X
272 reveal_type(x._asdict()) # N: Revealed type is "builtins.dict[builtins.str, Any]"
273
274 [builtins fixtures/dict.pyi]
275
276 [case testNewNamedTupleReplaceTyped]
277 from typing import NamedTuple
278
279 class X(NamedTuple):
280 x: int
281 y: str
282
283 x: X
284 reveal_type(x._replace()) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=__main__.X]"
285 x._replace(x=5)
286 x._replace(y=5) # E: Argument "y" to "_replace" of "X" has incompatible type "int"; expected "str"
287 [builtins fixtures/tuple.pyi]
288
289 [case testNewNamedTupleFields]
290 from typing import NamedTuple
291
292 class X(NamedTuple):
293 x: int
294 y: str
295
296 reveal_type(X._fields) # N: Revealed type is "tuple[builtins.str, builtins.str]"
297 reveal_type(X._field_types) # N: Revealed type is "builtins.dict[builtins.str, Any]"
298 reveal_type(X._field_defaults) # N: Revealed type is "builtins.dict[builtins.str, Any]"
299
300 # In typeshed's stub for builtins.pyi, __annotations__ is `dict[str, Any]`,
301 # but it's inferred as `Mapping[str, object]` here due to the fixture we're using
302 reveal_type(X.__annotations__) # N: Revealed type is "typing.Mapping[builtins.str, builtins.object]"
303
304 [builtins fixtures/dict-full.pyi]
305
306 [case testNewNamedTupleUnit]
307 from typing import NamedTuple
308
309 class X(NamedTuple):
310 pass
311
312 x: X = X()
313 x._replace()
314 x._fields[0] # E: Tuple index out of range
315 [builtins fixtures/tuple.pyi]
316
317 [case testNewNamedTupleJoinNamedTuple]
318 from typing import NamedTuple
319
320 class X(NamedTuple):
321 x: int
322 y: str
323 class Y(NamedTuple):
324 x: int
325 y: str
326
327 reveal_type([X(3, 'b'), Y(1, 'a')]) # N: Revealed type is "builtins.list[tuple[builtins.int, builtins.str]]"
328
329 [builtins fixtures/list.pyi]
330
331 [case testNewNamedTupleJoinTuple]
332 from typing import NamedTuple
333
334 class X(NamedTuple):
335 x: int
336 y: str
337
338 reveal_type([(3, 'b'), X(1, 'a')]) # N: Revealed type is "builtins.list[tuple[builtins.int, builtins.str]]"
339 reveal_type([X(1, 'a'), (3, 'b')]) # N: Revealed type is "builtins.list[tuple[builtins.int, builtins.str]]"
340
341 [builtins fixtures/list.pyi]
342
343 [case testNewNamedTupleWithTooManyArguments]
344 from typing import NamedTuple
345
346 class X(NamedTuple):
347 x: int
348 y = z = 2 # E: Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"
349 def f(self): pass
350 [builtins fixtures/tuple.pyi]
351
352 [case testNewNamedTupleWithInvalidItems2]
353 import typing
354
355 class X(typing.NamedTuple):
356 x: int
357 y = 1 # E: Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"
358 x.x: int # E: Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"
359 z: str = 'z'
360 aa: int # E: Non-default NamedTuple fields cannot follow default fields
361 [builtins fixtures/list.pyi]
362
363 [case testNewNamedTupleWithoutTypesSpecified]
364 from typing import NamedTuple
365
366 class X(NamedTuple):
367 x: int
368 y = 2 # E: Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"
369 [builtins fixtures/tuple.pyi]
370
371 [case testTypeUsingTypeCNamedTuple]
372 from typing import NamedTuple, Type
373
374 class N(NamedTuple):
375 x: int
376 y: str
377
378 def f(a: Type[N]):
379 a() # E: Missing positional arguments "x", "y" in call to "N"
380 [builtins fixtures/list.pyi]
381
382 [case testNewNamedTupleWithDefaults]
383 from typing import List, NamedTuple, Optional
384
385 class X(NamedTuple):
386 x: int
387 y: int = 2
388
389 reveal_type(X(1)) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.X]"
390 reveal_type(X(1, 2)) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.X]"
391
392 X(1, 'a') # E: Argument 2 to "X" has incompatible type "str"; expected "int"
393 X(1, z=3) # E: Unexpected keyword argument "z" for "X"
394
395 class HasNone(NamedTuple):
396 x: int
397 y: Optional[int] = None
398
399 reveal_type(HasNone(1)) # N: Revealed type is "tuple[builtins.int, builtins.int | None, fallback=__main__.HasNone]"
400
401 class Parameterized(NamedTuple):
402 x: int
403 y: List[int] = [1] + [2]
404 z: List[int] = []
405
406 reveal_type(Parameterized(1)) # N: Revealed type is "tuple[builtins.int, builtins.list[builtins.int], builtins.list[builtins.int], fallback=__main__.Parameterized]"
407 Parameterized(1, ['not an int']) # E: List item 0 has incompatible type "str"; expected "int"
408
409 class Default:
410 pass
411
412 class UserDefined(NamedTuple):
413 x: Default = Default()
414
415 reveal_type(UserDefined()) # N: Revealed type is "tuple[__main__.Default, fallback=__main__.UserDefined]"
416 reveal_type(UserDefined(Default())) # N: Revealed type is "tuple[__main__.Default, fallback=__main__.UserDefined]"
417 UserDefined(1) # E: Argument 1 to "UserDefined" has incompatible type "int"; expected "Default"
418
419 [builtins fixtures/list.pyi]
420
421 [case testNewNamedTupleWithDefaultsStrictOptional]
422 from typing import List, NamedTuple, Optional
423
424 class HasNone(NamedTuple):
425 x: int
426 y: Optional[int] = None
427
428 reveal_type(HasNone(1)) # N: Revealed type is "tuple[builtins.int, builtins.int | None, fallback=__main__.HasNone]"
429 HasNone(None) # E: Argument 1 to "HasNone" has incompatible type "None"; expected "int"
430 HasNone(1, y=None)
431 HasNone(1, y=2)
432
433 class CannotBeNone(NamedTuple):
434 x: int
435 y: int = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
436
437 [builtins fixtures/list.pyi]
438
439 [case testNewNamedTupleWrongType]
440 from typing import NamedTuple
441
442 class X(NamedTuple):
443 x: int
444 y: int = 'not an int' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
445 [builtins fixtures/tuple.pyi]
446
447 [case testNewNamedTupleErrorInDefault]
448 from typing import NamedTuple
449
450 class X(NamedTuple):
451 x: int = 1 + '1' # E: Unsupported left operand type for + ("int")
452 [builtins fixtures/tuple.pyi]
453
454 [case testNewNamedTupleInheritance]
455 from typing import NamedTuple
456
457 class X(NamedTuple):
458 x: str
459 y: int = 3
460
461 class Y(X):
462 def method(self) -> str:
463 self.y
464 return self.x
465
466 reveal_type(Y('a')) # N: Revealed type is "tuple[builtins.str, builtins.int, fallback=__main__.Y]"
467 Y(y=1, x='1').method()
468
469 class CallsBaseInit(X):
470 def __init__(self, x: str) -> None:
471 super().__init__(x) # E: Too many arguments for "__init__" of "object"
472 [builtins fixtures/tuple.pyi]
473
474 [case testNewNamedTupleWithMethods]
475 from typing import NamedTuple
476
477 class XMeth(NamedTuple):
478 x: int
479 def double(self) -> int:
480 return self.x
481 async def asyncdouble(self) -> int:
482 return self.x
483
484 class XRepr(NamedTuple):
485 x: int
486 y: int = 1
487 def __str__(self) -> str:
488 return 'string'
489 def __sub__(self, other: XRepr) -> int:
490 return 0
491
492 reveal_type(XMeth(1).double()) # N: Revealed type is "builtins.int"
493 _ = reveal_type(XMeth(1).asyncdouble()) # N: Revealed type is "typing.Coroutine[Any, Any, builtins.int]"
494 reveal_type(XMeth(42).x) # N: Revealed type is "builtins.int"
495 reveal_type(XRepr(42).__str__()) # N: Revealed type is "builtins.str"
496 reveal_type(XRepr(1, 2).__sub__(XRepr(3))) # N: Revealed type is "builtins.int"
497 [typing fixtures/typing-async.pyi]
498 [builtins fixtures/tuple.pyi]
499
500 [case testNewNamedTupleOverloading]
501 from typing import NamedTuple, overload
502
503 class Overloader(NamedTuple):
504 x: int
505 @overload
506 def method(self, y: str) -> str: pass
507 @overload
508 def method(self, y: int) -> int: pass
509 def method(self, y):
510 return y
511
512 reveal_type(Overloader(1).method('string')) # N: Revealed type is "builtins.str"
513 reveal_type(Overloader(1).method(1)) # N: Revealed type is "builtins.int"
514 Overloader(1).method(('tuple',)) # E: No overload variant of "method" of "Overloader" matches argument type "tuple[str]" \
515 # N: Possible overload variants: \
516 # N: def method(self, y: str) -> str \
517 # N: def method(self, y: int) -> int
518 [builtins fixtures/tuple.pyi]
519
520 [case testNewNamedTupleMethodInheritance]
521 from typing import NamedTuple, TypeVar
522
523 T = TypeVar('T')
524
525 class Base(NamedTuple):
526 x: int
527 def copy(self: T) -> T:
528 reveal_type(self) # N: Revealed type is "T`-1"
529 return self
530 def good_override(self) -> int:
531 reveal_type(self) # N: Revealed type is "tuple[builtins.int, fallback=__main__.Base]"
532 reveal_type(self[0]) # N: Revealed type is "builtins.int"
533 self[0] = 3 # E: Unsupported target for indexed assignment ("Base")
534 reveal_type(self.x) # N: Revealed type is "builtins.int"
535 self.x = 3 # E: Property "x" defined in "Base" is read-only
536 self[1] # E: Tuple index out of range
537 reveal_type(self[T]) # N: Revealed type is "builtins.int" \
538 # E: No overload variant of "__getitem__" of "tuple" matches argument type "TypeVar" \
539 # N: Possible overload variants: \
540 # N: def __getitem__(self, int, /) -> int \
541 # N: def __getitem__(self, slice[int | None], /) -> tuple[int, ...]
542 return self.x
543 def bad_override(self) -> int:
544 return self.x
545
546 class Child(Base):
547 def new_method(self) -> int:
548 reveal_type(self) # N: Revealed type is "tuple[builtins.int, fallback=__main__.Child]"
549 reveal_type(self[0]) # N: Revealed type is "builtins.int"
550 self[0] = 3 # E: Unsupported target for indexed assignment ("Child")
551 reveal_type(self.x) # N: Revealed type is "builtins.int"
552 self.x = 3 # E: Property "x" defined in "Base" is read-only
553 self[1] # E: Tuple index out of range
554 return self.x
555 def good_override(self) -> int:
556 return 0
557 def bad_override(self) -> str: # E: Return type "str" of "bad_override" incompatible with return type "int" in supertype "Base"
558 return 'incompatible'
559
560 def takes_base(base: Base) -> int:
561 return base.x
562
563 reveal_type(Base(1).copy()) # N: Revealed type is "tuple[builtins.int, fallback=__main__.Base]"
564 reveal_type(Child(1).copy()) # N: Revealed type is "tuple[builtins.int, fallback=__main__.Child]"
565 reveal_type(Base(1).good_override()) # N: Revealed type is "builtins.int"
566 reveal_type(Child(1).good_override()) # N: Revealed type is "builtins.int"
567 reveal_type(Base(1).bad_override()) # N: Revealed type is "builtins.int"
568 reveal_type(takes_base(Base(1))) # N: Revealed type is "builtins.int"
569 reveal_type(takes_base(Child(1))) # N: Revealed type is "builtins.int"
570 [builtins fixtures/tuple.pyi]
571 [typing fixtures/typing-full.pyi]
572
573 [case testNewNamedTupleIllegalNames]
574 from typing import Callable, NamedTuple
575
576 class XMethBad(NamedTuple):
577 x: int
578 def _fields(self): # E: Cannot overwrite NamedTuple attribute "_fields"
579 return 'no chance for this'
580
581 class MagicalFields(NamedTuple):
582 x: int
583 def __slots__(self) -> None: pass # E: Cannot overwrite NamedTuple attribute "__slots__"
584 def __new__(cls) -> MagicalFields: pass # E: Cannot overwrite NamedTuple attribute "__new__"
585 def _source(self) -> int: pass # E: Cannot overwrite NamedTuple attribute "_source"
586 __annotations__ = {'x': float} # E: NamedTuple field name cannot start with an underscore: __annotations__ \
587 # E: Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]" \
588 # E: Cannot overwrite NamedTuple attribute "__annotations__"
589
590 class AnnotationsAsAMethod(NamedTuple):
591 x: int
592 # This fails at runtime because typing.py assumes that __annotations__ is a dictionary.
593 def __annotations__(self) -> float: # E: Cannot overwrite NamedTuple attribute "__annotations__"
594 return 1.0
595
596 class ReuseNames(NamedTuple):
597 x: int
598 def x(self) -> str: # E: Name "x" already defined on line 22
599 return ''
600
601 def y(self) -> int:
602 return 0
603 y: str # E: Name "y" already defined on line 26
604
605 class ReuseCallableNamed(NamedTuple):
606 z: Callable[[ReuseNames], int]
607 def z(self) -> int: # E: Name "z" already defined on line 31
608 return 0
609
610 [builtins fixtures/dict.pyi]
611
612 [case testNewNamedTupleDocString]
613 from typing import NamedTuple
614
615 class Documented(NamedTuple):
616 """This is a docstring."""
617 x: int
618
619 reveal_type(Documented.__doc__) # N: Revealed type is "builtins.str"
620 reveal_type(Documented(1).x) # N: Revealed type is "builtins.int"
621
622 class BadDoc(NamedTuple):
623 x: int
624 def __doc__(self) -> str:
625 return ''
626
627 reveal_type(BadDoc(1).__doc__()) # N: Revealed type is "builtins.str"
628 [builtins fixtures/tuple.pyi]
629
630 [case testNewNamedTupleClassMethod]
631 from typing import NamedTuple
632
633 class HasClassMethod(NamedTuple):
634 x: str
635
636 @classmethod
637 def new(cls, f: str) -> 'HasClassMethod':
638 reveal_type(cls) # N: Revealed type is "type[tuple[builtins.str, fallback=__main__.HasClassMethod]]"
639 reveal_type(HasClassMethod) # N: Revealed type is "def (x: builtins.str) -> tuple[builtins.str, fallback=__main__.HasClassMethod]"
640 return cls(x=f)
641
642 [builtins fixtures/classmethod.pyi]
643
644 [case testNewNamedTupleStaticMethod]
645 from typing import NamedTuple
646
647 class HasStaticMethod(NamedTuple):
648 x: str
649
650 @staticmethod
651 def new(f: str) -> 'HasStaticMethod':
652 return HasStaticMethod(x=f)
653
654 [builtins fixtures/classmethod.pyi]
655
656 [case testNewNamedTupleProperty]
657 from typing import NamedTuple
658
659 class HasStaticMethod(NamedTuple):
660 x: str
661
662 @property
663 def size(self) -> int:
664 reveal_type(self) # N: Revealed type is "tuple[builtins.str, fallback=__main__.HasStaticMethod]"
665 return 4
666
667 [builtins fixtures/property.pyi]
668
669 [case testTypingExtensionsNamedTuple]
670 from typing_extensions import NamedTuple
671
672 class Point(NamedTuple):
673 x: int
674 y: int
675
676 bad_point = Point('foo') # E: Missing positional argument "y" in call to "Point" \
677 # E: Argument 1 to "Point" has incompatible type "str"; expected "int"
678 point = Point(1, 2)
679 x, y = point
680 x = point.x
681 reveal_type(x) # N: Revealed type is "builtins.int"
682 reveal_type(y) # N: Revealed type is "builtins.int"
683 point.y = 6 # E: Property "y" defined in "Point" is read-only
684
685 [builtins fixtures/tuple.pyi]