Debian Codegraph @

test-data/unit/check-classes.test

raw
1 -- Methods
2 -- -------
3
4
5 [case testMethodCall]
6 class A:
7 def foo(self, x: 'A') -> None: pass
8 class B:
9 def bar(self, x: 'B', y: A) -> None: pass
10
11 a: A
12 b: B
13
14 a.foo(B()) # E: Argument 1 to "foo" of "A" has incompatible type "B"; expected "A"
15 a.bar(B(), A()) # E: "A" has no attribute "bar"
16
17 a.foo(A())
18 b.bar(B(), A())
19
20 [case testMethodCallWithSubtype]
21 class A:
22 def foo(self, x: 'A') -> None: pass
23 def bar(self, x: 'B') -> None: pass
24 class B(A): pass
25
26 a: A
27 a.foo(A())
28 a.foo(B())
29 a.bar(A()) # E: Argument 1 to "bar" of "A" has incompatible type "A"; expected "B"
30 a.bar(B())
31
32 [case testInheritingMethod]
33 class A:
34 def foo(self, x: 'B') -> None: pass
35 class B(A): pass
36
37 a: B
38 a.foo(A()) # Fail
39 a.foo(B())
40
41 [targets __main__, __main__.A.foo]
42 [out]
43 main:6: error: Argument 1 to "foo" of "A" has incompatible type "A"; expected "B"
44
45 [case testMethodCallWithInvalidNumberOfArguments]
46 class A:
47 def foo(self, x: 'A') -> None: pass
48
49 a: A
50 a.foo() # Fail
51 a.foo(object(), A()) # Fail
52 [out]
53 main:5: error: Missing positional argument "x" in call to "foo" of "A"
54 main:6: error: Too many arguments for "foo" of "A"
55 main:6: error: Argument 1 to "foo" of "A" has incompatible type "object"; expected "A"
56
57 [case testMethodBody]
58 import typing
59 class A:
60 def f(self) -> None:
61 a = object() # type: A # Fail
62 [out]
63 main:4: error: Incompatible types in assignment (expression has type "object", variable has type "A")
64
65 [case testMethodArguments]
66 import typing
67 class A:
68 def f(self, a: 'A', b: 'B') -> None:
69 if int():
70 a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
71 b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
72 a = A()
73 b = B()
74 a = a
75 a = b # E: Incompatible types in assignment (expression has type "B", variable has type "A")
76 class B: pass
77 [out]
78
79 [case testReturnFromMethod]
80 import typing
81 class A:
82 def f(self) -> 'A':
83 return B() # Fail
84 return A()
85 class B: pass
86 [out]
87 main:4: error: Incompatible return value type (got "B", expected "A")
88
89 [case testSelfArgument]
90 import typing
91 class A:
92 def f(self) -> None:
93 o = self # type: B # Fail
94 self.g() # Fail
95 a = self # type: A
96 self.f()
97 class B: pass
98 [out]
99 main:4: error: Incompatible types in assignment (expression has type "A", variable has type "B")
100 main:5: error: "A" has no attribute "g"
101
102 [case testAssignToMethodViaInstance]
103 import typing
104 class A:
105 def f(self): pass
106 A().f = None # E: Cannot assign to a method \
107 # E: Incompatible types in assignment (expression has type "None", variable has type "Callable[[], Any]")
108
109
110 [case testOverrideAttributeWithMethod]
111 # This was crashing:
112 # https://github.com/python/mypy/issues/10134
113 from typing import Protocol
114
115 class Base:
116 __hash__: None = None
117
118 class Derived(Base):
119 def __hash__(self) -> int: # E: Signature of "__hash__" incompatible with supertype "Base" \
120 # N: Superclass: \
121 # N: None \
122 # N: Subclass: \
123 # N: def __hash__(self) -> int
124 pass
125
126 # Correct:
127
128 class CallableProtocol(Protocol):
129 def __call__(self, arg: int) -> int:
130 pass
131
132 class CorrectBase:
133 attr: CallableProtocol
134
135 class CorrectDerived(CorrectBase):
136 def attr(self, arg: int) -> int:
137 pass
138
139 [case testOverrideMethodWithAttribute]
140 # The reverse should not crash as well:
141 from typing import Callable
142
143 class Base:
144 def __hash__(self) -> int:
145 pass
146
147 class Derived(Base):
148 __hash__ = 1 # E: Incompatible types in assignment (expression has type "int", base class "Base" defined the type as "Callable[[], int]")
149
150 [case testOverridePartialAttributeWithMethod]
151 # This was crashing: https://github.com/python/mypy/issues/11686.
152 class Base:
153 def __init__(self, arg: int):
154 self.partial_type = [] # E: Need type annotation for "partial_type" (hint: "partial_type: list[<type>] = ...")
155 self.force_deferral = []
156
157 # Force inference of the `force_deferral` attribute in `__init__` to be
158 # deferred to a later pass by providing a definition in another context,
159 # which means `partial_type` remains only partially inferred.
160 force_deferral = [] # E: Need type annotation for "force_deferral" (hint: "force_deferral: list[<type>] = ...")
161
162
163 class Derived(Base):
164 def partial_type(self) -> int: # E: Signature of "partial_type" incompatible with supertype "Base" \
165 # N: Superclass: \
166 # N: list[Any] \
167 # N: Subclass: \
168 # N: def partial_type(self) -> int
169 ...
170
171
172 -- Attributes
173 -- ----------
174
175
176 [case testReferToInvalidAttribute]
177
178 class A:
179 def __init__(self) -> None:
180 self.x = object()
181 a: A
182 a.y # E: "A" has no attribute "y"
183 a.y = object() # E: "A" has no attribute "y"
184 a.x
185 a.x = object()
186
187 [case testReferToInvalidAttributeUnannotatedInit]
188 class A:
189 def __init__(self):
190 self.x = object()
191
192 a: A
193 a.y # E: "A" has no attribute "y"
194 a.y = object() # E: "A" has no attribute "y"
195 a.x
196 a.x = object()
197
198 [case testArgumentTypeInference]
199
200 class A:
201 def __init__(self, aa: 'A', bb: 'B') -> None:
202 self.a = aa
203 self.b = bb
204 class B: pass
205 a: A
206 b: B
207 a.a = b # Fail
208 a.b = a # Fail
209 b.a # Fail
210 a.a = a
211 a.b = b
212 [out]
213 main:9: error: Incompatible types in assignment (expression has type "B", variable has type "A")
214 main:10: error: Incompatible types in assignment (expression has type "A", variable has type "B")
215 main:11: error: "B" has no attribute "a"
216
217 [case testExplicitAttributeInBody]
218
219 class A:
220 x: A
221 a: A
222 a.x = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
223 a.x = A()
224
225 [case testAttributeDefinedInNonInitMethod]
226 import typing
227 class A:
228 def f(self) -> None:
229 self.x = 1
230 self.y = ''
231 self.x = 1
232 a = A()
233 a.x = 1
234 a.y = ''
235 a.x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
236 a.z = 0 # E: "A" has no attribute "z"
237
238 [case testInheritanceAndAttributeAssignment]
239 import typing
240 class A:
241 def f(self) -> None:
242 self.x = 0
243 class B(A):
244 def f(self) -> None:
245 self.x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
246 [targets __main__, __main__.A.f, __main__.B.f]
247
248 [case testAssignmentToAttributeInMultipleMethods]
249 import typing
250 class A:
251 def f(self) -> None:
252 self.x = 0
253 def g(self) -> None:
254 self.x = '' # Fail
255 def __init__(self) -> None:
256 self.x = '' # Fail
257 [out]
258 main:6: error: Incompatible types in assignment (expression has type "str", variable has type "int")
259 main:8: error: Incompatible types in assignment (expression has type "str", variable has type "int")
260
261 [case testClassNamesDefinedOnSelUsedInClassBody]
262 class A(object):
263 def f(self):
264 self.attr = 1
265 attr = 0
266
267 class B(object):
268 attr = 0
269 def f(self):
270 self.attr = 1
271
272 class C(object):
273 attr = 0
274 def f(self):
275 self.attr = 1
276 attr = 0
277
278 class D(object):
279 def g(self):
280 self.attr = 1
281 attr = 0
282 def f(self):
283 self.attr = 1
284 [out]
285
286 [case testClassNamesDefinedOnSelUsedInClassBodyReveal]
287
288 class A(object):
289 def f(self) -> None:
290 self.attr = 1
291 attr # E: Name "attr" is not defined
292
293 class B(object):
294 attr = 0
295 def f(self) -> None:
296 reveal_type(self.attr) # N: Revealed type is "builtins.int"
297 [out]
298
299
300 -- Method overriding
301 -- -----------------
302
303
304 [case testMethodOverridingWithIdenticalSignature]
305 import typing
306 class A:
307 def f(self, x: 'A') -> None: pass
308 def g(self, x: 'B' , y: object) -> 'A': pass
309 def h(self) -> None: pass
310 class B(A):
311 def f(self, x: A) -> None: pass
312 def g(self, x: 'B' , y: object) -> A: pass
313 def h(self) -> None: pass
314 [out]
315
316 [case testMethodOverridingWithCovariantType]
317 import typing
318 class A:
319 def f(self, x: 'A', y: 'B') -> 'A': pass
320 def g(self, x: 'A', y: 'B') -> 'A': pass
321 class B(A):
322 def f(self, x: A, y: 'B') -> 'B': pass
323 def g(self, x: A, y: A) -> 'A': pass
324 [out]
325
326 [case testMethodOverridingWithIncompatibleTypes]
327 import typing
328 class A:
329 def f(self, x: 'A', y: 'B') -> 'A': pass
330 def g(self, x: 'A', y: 'B') -> 'A': pass
331 def h(self, x: 'A', y: 'B') -> 'A': pass
332 class B(A):
333 def f(self, x: 'B', y: 'B') -> A: pass # Fail
334 def g(self, x: A, y: A) -> A: pass
335 def h(self, x: A, y: 'B') -> object: pass # Fail
336 [out]
337 main:7: error: Argument 1 of "f" is incompatible with supertype "A"; supertype defines the argument type as "A"
338 main:7: note: This violates the Liskov substitution principle
339 main:7: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
340 main:9: error: Return type "object" of "h" incompatible with return type "A" in supertype "A"
341
342 [case testMethodOverridingWithIncompatibleTypesOnMultipleLines]
343 class A:
344 def f(self, x: int, y: str) -> None: pass
345 class B(A):
346 def f(
347 self,
348 x: int,
349 y: bool,
350 ) -> None:
351 pass
352 [out]
353 main:7: error: Argument 2 of "f" is incompatible with supertype "A"; supertype defines the argument type as "str"
354 main:7: note: This violates the Liskov substitution principle
355 main:7: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
356
357 [case testMultiLineMethodOverridingWithIncompatibleTypesIgnorableAtArgument]
358 class A:
359 def f(self, x: int, y: str) -> None: pass
360
361 class B(A):
362 def f(
363 self,
364 x: int,
365 y: bool, # type: ignore[override]
366 ) -> None:
367 pass
368
369 [case testMultiLineMethodOverridingWithIncompatibleTypesIgnorableAtDefinition]
370 class A:
371 def f(self, x: int, y: str) -> None: pass
372 class B(A):
373 def f( # type: ignore[override]
374 self,
375 x: int,
376 y: bool,
377 ) -> None:
378 pass
379
380 [case testMultiLineMethodOverridingWithIncompatibleTypesWrongIgnore]
381 class A:
382 def f(self, x: int, y: str) -> None: pass
383 class B(A):
384 def f( # type: ignore[return-type]
385 self,
386 x: int,
387 y: bool,
388 ) -> None:
389 pass
390 [out]
391 main:7: error: Argument 2 of "f" is incompatible with supertype "A"; supertype defines the argument type as "str"
392 main:7: note: This violates the Liskov substitution principle
393 main:7: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
394
395 [case testEqMethodsOverridingWithNonObjects]
396 class A:
397 def __eq__(self, other: A) -> bool: pass # Fail
398 [builtins fixtures/plugin_attrs.pyi]
399 [out]
400 main:2: error: Argument 1 of "__eq__" is incompatible with supertype "builtins.object"; supertype defines the argument type as "object"
401 main:2: note: This violates the Liskov substitution principle
402 main:2: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
403 main:2: note: It is recommended for "__eq__" to work with arbitrary objects, for example:
404 main:2: note: def __eq__(self, other: object) -> bool:
405 main:2: note: if not isinstance(other, A):
406 main:2: note: return NotImplemented
407 main:2: note: return <logic to compare two A instances>
408
409 [case testMethodOverridingWithIncompatibleArgumentCount]
410 import typing
411 class A:
412 def f(self, x: 'A') -> None: pass
413 def g(self, x: 'A', y: 'B') -> 'A': pass
414 class B(A):
415 def f(self, x: A, y: A) -> None: pass # Fail
416 def g(self, x: A) -> A: pass # Fail
417 [out]
418 main:6: error: Signature of "f" incompatible with supertype "A"
419 main:6: note: Superclass:
420 main:6: note: def f(self, x: A) -> None
421 main:6: note: Subclass:
422 main:6: note: def f(self, x: A, y: A) -> None
423 main:7: error: Signature of "g" incompatible with supertype "A"
424 main:7: note: Superclass:
425 main:7: note: def g(self, x: A, y: B) -> A
426 main:7: note: Subclass:
427 main:7: note: def g(self, x: A) -> A
428
429 [case testMethodOverridingAcrossDeepInheritanceHierarchy1]
430 import typing
431 class A:
432 def f(self, x: 'B') -> None: pass
433 class B(A): pass
434 class C(B): # with gap in implementations
435 def f(self, x: 'C') -> None: # Fail
436 pass
437 [out]
438 main:6: error: Argument 1 of "f" is incompatible with supertype "A"; supertype defines the argument type as "B"
439 main:6: note: This violates the Liskov substitution principle
440 main:6: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
441
442 [case testMethodOverridingAcrossDeepInheritanceHierarchy2]
443 import typing
444 class A:
445 def f(self) -> 'B': pass
446 class B(A):
447 def f(self) -> 'C': pass
448 class C(B): # with multiple implementations
449 def f(self) -> B: # Fail
450 pass
451 [out]
452 main:7: error: Return type "B" of "f" incompatible with return type "C" in supertype "B"
453
454 [case testMethodOverridingWithVoidReturnValue]
455 import typing
456 class A:
457 def f(self) -> None: pass
458 def g(self) -> 'A': pass
459 class B(A):
460 def f(self) -> A: pass # Fail
461 def g(self) -> None: pass # Fail
462 [out]
463 main:6: error: Return type "A" of "f" incompatible with return type "None" in supertype "A"
464 main:7: error: Return type "None" of "g" incompatible with return type "A" in supertype "A"
465
466 [case testOverride__new__WithDifferentSignature]
467 class A:
468 def __new__(cls, x: int) -> A:
469 pass
470
471 class B(A):
472 def __new__(cls) -> B:
473 pass
474
475 [case testOverride__new__WithLiteralReturnPassing]
476 from typing import Literal
477
478 class Falsy:
479 def __bool__(self) -> Literal[False]: pass
480
481 reveal_type(bool(Falsy())) # N: Revealed type is "Literal[False]"
482 reveal_type(int()) # N: Revealed type is "Literal[0]"
483
484 [builtins fixtures/literal__new__.pyi]
485 [typing fixtures/typing-medium.pyi]
486
487 [case testOverride__new__WithLiteralReturnFailing]
488 from typing import Literal
489
490 class Foo:
491 def __new__(cls) -> Literal[1]: pass # E: Incompatible return type for "__new__" (returns "Literal[1]", but must return a subtype of "Foo")
492
493 [builtins fixtures/__new__.pyi]
494 [typing fixtures/typing-medium.pyi]
495
496 [case testOverride__new__AndCallObject]
497 from typing import TypeVar, Generic
498
499 class A:
500 def __new__(cls, x: int) -> 'A':
501 return object.__new__(cls)
502
503 T = TypeVar('T')
504 class B(Generic[T]):
505 def __new__(cls, foo: T) -> 'B[T]':
506 x = object.__new__(cls)
507 # object.__new__ doesn't have a great type :(
508 reveal_type(x) # N: Revealed type is "Any"
509 return x
510
511 [builtins fixtures/__new__.pyi]
512
513 [case testInnerFunctionNotOverriding]
514 class A:
515 def f(self) -> int: pass
516
517 class B(A):
518 def g(self) -> None:
519 def f(self) -> str: pass
520
521 [case testOverride__init_subclass__WithDifferentSignature]
522 class A:
523 def __init_subclass__(cls, x: int) -> None: pass
524 class B(A): # E: Missing positional argument "x" in call to "__init_subclass__" of "A"
525 def __init_subclass__(cls) -> None: pass
526
527 [case testOverrideWithDecorator]
528 from typing import Callable
529
530 def int_to_none(f: Callable[..., int]) -> Callable[..., None]: ...
531 def str_to_int(f: Callable[..., str]) -> Callable[..., int]: ...
532
533 class A:
534 def f(self) -> None: pass
535 def g(self) -> str: pass
536 def h(self) -> None: pass
537
538 class B(A):
539 @int_to_none
540 def f(self) -> int: pass
541 @str_to_int
542 def g(self) -> str: pass # Fail
543 @int_to_none
544 @str_to_int
545 def h(self) -> str: pass
546 [out]
547 main:15: error: Signature of "g" incompatible with supertype "A"
548 main:15: note: Superclass:
549 main:15: note: def g(self) -> str
550 main:15: note: Subclass:
551 main:15: note: def g(*Any, **Any) -> int
552
553 [case testOverrideDecorated]
554 from typing import Callable
555
556 def str_to_int(f: Callable[..., str]) -> Callable[..., int]: ...
557
558 class A:
559 @str_to_int
560 def f(self) -> str: pass
561 @str_to_int
562 def g(self) -> str: pass
563 @str_to_int
564 def h(self) -> str: pass
565
566 class B(A):
567 def f(self) -> int: pass
568 def g(self) -> str: pass # Fail
569 @str_to_int
570 def h(self) -> str: pass
571 [out]
572 main:15: error: Signature of "g" incompatible with supertype "A"
573 main:15: note: Superclass:
574 main:15: note: def g(*Any, **Any) -> int
575 main:15: note: Subclass:
576 main:15: note: def g(self) -> str
577
578 [case testOverrideWithDecoratorReturningAny]
579 def dec(f): pass
580
581 class A:
582 def f(self) -> str: pass
583
584 class B(A):
585 @dec
586 def f(self) -> int: pass
587
588 [case testOverrideWithDecoratorReturningCallable]
589 from typing import Any, Callable, TypeVar
590
591 class Base:
592 def get(self, a: str) -> None: ...
593
594 def dec(fn: Any) -> Callable[[Any, int], None]: ...
595
596 class Derived(Base):
597 @dec
598 def get(self) -> None: ... # E: Argument 1 of "get" is incompatible with supertype "Base"; supertype defines the argument type as "str" \
599 # N: This violates the Liskov substitution principle \
600 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
601 [builtins fixtures/tuple.pyi]
602
603 [case testOverrideWithDecoratorReturningCallable2]
604 # flags: --pretty
605 from typing import Any, Callable, TypeVar
606
607 _C = TypeVar("_C", bound=Callable[..., Any])
608
609 def infer_signature(f: _C) -> Callable[[Any], _C]: ...
610
611 class Base:
612 def get(self, a: str, b: str, c: str) -> None: ...
613 def post(self, a: str, b: str) -> None: ...
614
615 # Third argument incompatible
616 def get(self, a: str, b: str, c: int) -> None: ...
617
618 # Second argument incompatible - still should not map to **kwargs
619 def post(self, a: str, b: int) -> None: ...
620
621 class Derived(Base):
622 @infer_signature(get)
623 def get(self, *args: Any, **kwargs: Any) -> None: ...
624
625 @infer_signature(post)
626 def post(self, *args: Any, **kwargs: Any) -> None: ...
627 [builtins fixtures/tuple.pyi]
628 [out]
629 main:20: error: Argument 3 of "get" is incompatible with supertype "Base"; supertype defines the argument type as "str"
630 def get(self, *args: Any, **kwargs: Any) -> None: ...
631 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
632 main:20: note: This violates the Liskov substitution principle
633 main:20: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
634 main:23: error: Argument 2 of "post" is incompatible with supertype "Base"; supertype defines the argument type as "str"
635 def post(self, *args: Any, **kwargs: Any) -> None: ...
636 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
637 main:23: note: This violates the Liskov substitution principle
638 main:23: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
639
640 [case testOverrideWithDecoratorReturningInstance]
641 def dec(f) -> str: pass
642
643 class A:
644 def f(self) -> str: pass
645 @dec
646 def g(self) -> int: pass
647 @dec
648 def h(self) -> int: pass
649
650 class B(A):
651 @dec
652 def f(self) -> int: pass # E: Signature of "f" incompatible with supertype "A" \
653 # N: Superclass: \
654 # N: def f(self) -> str \
655 # N: Subclass: \
656 # N: str
657 def g(self) -> int: pass # E: Signature of "g" incompatible with supertype "A" \
658 # N: Superclass: \
659 # N: str \
660 # N: Subclass: \
661 # N: def g(self) -> int
662 @dec
663 def h(self) -> str: pass
664
665 [case testOverrideIncompatibleWithMultipleSupertypes]
666 class A:
667 def f(self, *, a: int) -> None:
668 return
669
670 class B(A):
671 def f(self, *, b: int) -> None: # E: Signature of "f" incompatible with supertype "A" \
672 # N: Superclass: \
673 # N: def f(self, *, a: int) -> None \
674 # N: Subclass: \
675 # N: def f(self, *, b: int) -> None
676 return
677
678 class C(B):
679 def f(self, *, c: int) -> None: # E: Signature of "f" incompatible with supertype "B" \
680 # N: Superclass: \
681 # N: def f(self, *, b: int) -> None \
682 # N: Subclass: \
683 # N: def f(self, *, c: int) -> None \
684 # E: Signature of "f" incompatible with supertype "A" \
685 # N: Superclass: \
686 # N: def f(self, *, a: int) -> None \
687 # N: Subclass: \
688 # N: def f(self, *, c: int) -> None
689 return
690
691 [case testOverrideStaticMethodWithStaticMethod]
692 class A:
693 @staticmethod
694 def f(x: int, y: str) -> None: pass
695 @staticmethod
696 def g(x: int, y: str) -> None: pass
697
698 class B(A):
699 @staticmethod
700 def f(x: int, y: str) -> None: pass
701 @staticmethod
702 def g(x: str, y: str) -> None: pass # E: Argument 1 of "g" is incompatible with supertype "A"; supertype defines the argument type as "int" \
703 # N: This violates the Liskov substitution principle \
704 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
705 [builtins fixtures/classmethod.pyi]
706
707 [case testOverrideClassMethodWithClassMethod]
708 class A:
709 @classmethod
710 def f(cls, x: int, y: str) -> None: pass
711 @classmethod
712 def g(cls, x: int, y: str) -> None: pass
713
714 class B(A):
715 @classmethod
716 def f(cls, x: int, y: str) -> None: pass
717 @classmethod
718 def g(cls, x: str, y: str) -> None: pass # E: Argument 1 of "g" is incompatible with supertype "A"; supertype defines the argument type as "int" \
719 # N: This violates the Liskov substitution principle \
720 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
721 [builtins fixtures/classmethod.pyi]
722
723 [case testOverrideClassMethodWithStaticMethod]
724 class A:
725 @classmethod
726 def f(cls, x: int) -> None: pass
727 @classmethod
728 def g(cls, x: int) -> int: pass
729 @classmethod
730 def h(cls) -> int: pass
731
732 class B(A):
733 @staticmethod
734 def f(x: int) -> None: pass
735 @staticmethod
736 def g(x: str) -> int: pass # E: Argument 1 of "g" is incompatible with supertype "A"; supertype defines the argument type as "int" \
737 # N: This violates the Liskov substitution principle \
738 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
739 @staticmethod
740 def h() -> int: pass
741 [builtins fixtures/classmethod.pyi]
742
743 [case testOverrideStaticMethodWithClassMethod]
744 class A:
745 @staticmethod
746 def f(x: int) -> None: pass
747 @staticmethod
748 def g(x: str) -> int: pass
749 @staticmethod
750 def h() -> int: pass
751
752 class B(A):
753 @classmethod
754 def f(cls, x: int) -> None: pass
755 @classmethod
756 def g(cls, x: int) -> int: pass # E: Argument 1 of "g" is incompatible with supertype "A"; supertype defines the argument type as "str" \
757 # N: This violates the Liskov substitution principle \
758 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
759 @classmethod
760 def h(cls) -> int: pass
761 [builtins fixtures/classmethod.pyi]
762
763 [case testOverrideReplaceMethod]
764 # flags: --show-error-codes
765 from typing import Optional
766 from typing_extensions import Self
767 class A:
768 def __replace__(self, x: Optional[str]) -> Self: pass
769
770 class B(A):
771 def __replace__(self, x: str) -> Self: pass # E: \
772 # E: Argument 1 of "__replace__" is incompatible with supertype "A"; supertype defines the argument type as "str | None" [override] \
773 # N: This violates the Liskov substitution principle \
774 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
775 [builtins fixtures/tuple.pyi]
776
777 [case testAllowCovarianceInReadOnlyAttributes]
778 from typing import Callable, TypeVar
779
780 T = TypeVar('T')
781
782 class X:
783 pass
784
785
786 class Y(X):
787 pass
788
789 def dec(f: Callable[..., T]) -> T: pass
790
791 class A:
792 @dec
793 def f(self) -> X: pass
794
795 class B(A):
796 @dec
797 def f(self) -> Y: pass
798
799 [case testOverrideCallableAttributeWithMethod]
800 from typing import Callable
801
802 class A:
803 f1: Callable[[str], None]
804 f2: Callable[[str], None]
805 f3: Callable[[str], None]
806
807 class B(A):
808 def f1(self, x: object) -> None:
809 pass
810
811 @classmethod
812 def f2(cls, x: object) -> None:
813 pass
814
815 @staticmethod
816 def f3(x: object) -> None:
817 pass
818 [builtins fixtures/classmethod.pyi]
819
820 [case testOverrideCallableAttributeWithMethodMutableOverride]
821 # flags: --enable-error-code=mutable-override
822 from typing import Callable
823
824 class A:
825 f1: Callable[[str], None]
826 f2: Callable[[str], None]
827 f3: Callable[[str], None]
828
829 class B(A):
830 def f1(self, x: object) -> None: pass # E: Covariant override of a mutable attribute (base class "A" defined the type as "Callable[[str], None]", override has type "Callable[[object], None]")
831
832 @classmethod
833 def f2(cls, x: object) -> None: pass # E: Covariant override of a mutable attribute (base class "A" defined the type as "Callable[[str], None]", override has type "Callable[[object], None]")
834
835 @staticmethod
836 def f3(x: object) -> None: pass # E: Covariant override of a mutable attribute (base class "A" defined the type as "Callable[[str], None]", override has type "Callable[[object], None]")
837 [builtins fixtures/classmethod.pyi]
838
839 [case testOverrideCallableAttributeWithSettableProperty]
840 from typing import Callable
841
842 class A:
843 f: Callable[[str], None]
844
845 class B(A):
846 @property
847 def f(self) -> Callable[[object], None]: pass
848 @f.setter
849 def f(self, x: object) -> None: pass
850 [builtins fixtures/property.pyi]
851
852 [case testOverrideCallableAttributeWithSettablePropertyMutableOverride]
853 # flags: --enable-error-code=mutable-override
854 from typing import Callable
855
856 class A:
857 f: Callable[[str], None]
858
859 class B(A):
860 @property
861 def f(self) -> Callable[[object], None]: pass
862 @f.setter
863 def f(self, x: object) -> None: pass
864 [builtins fixtures/property.pyi]
865
866 [case testOverrideCallableUnionAttributeWithMethod]
867 from typing import Callable, Union
868
869 class A:
870 f1: Union[Callable[[str], str], str]
871 f2: Union[Callable[[str], str], str]
872 f3: Union[Callable[[str], str], str]
873 f4: Union[Callable[[str], str], str]
874
875 class B(A):
876 def f1(self, x: str) -> str:
877 pass
878
879 def f2(self, x: object) -> str:
880 pass
881
882 @classmethod
883 def f3(cls, x: str) -> str:
884 pass
885
886 @staticmethod
887 def f4(x: str) -> str:
888 pass
889 [builtins fixtures/classmethod.pyi]
890
891 [case testOverrideCallableUnionAttributeWithMethodMutableOverride]
892 # flags: --enable-error-code=mutable-override
893 from typing import Callable, Union
894
895 class A:
896 f1: Union[Callable[[str], str], str]
897 f2: Union[Callable[[str], str], str]
898 f3: Union[Callable[[str], str], str]
899 f4: Union[Callable[[str], str], str]
900
901 class B(A):
902 def f1(self, x: str) -> str: # E: Covariant override of a mutable attribute (base class "A" defined the type as "Callable[[str], str] | str", override has type "Callable[[str], str]")
903 pass
904
905 def f2(self, x: object) -> str: # E: Covariant override of a mutable attribute (base class "A" defined the type as "Callable[[str], str] | str", override has type "Callable[[object], str]")
906 pass
907
908 @classmethod
909 def f3(cls, x: str) -> str: # E: Covariant override of a mutable attribute (base class "A" defined the type as "Callable[[str], str] | str", override has type "Callable[[str], str]")
910 pass
911
912 @staticmethod
913 def f4(x: str) -> str: # E: Covariant override of a mutable attribute (base class "A" defined the type as "Callable[[str], str] | str", override has type "Callable[[str], str]")
914 pass
915 [builtins fixtures/classmethod.pyi]
916
917 -- Constructors
918 -- ------------
919
920
921 [case testTrivialConstructor]
922 class A:
923 def __init__(self) -> None: pass
924
925 a = A() # type: A
926 b = A() # type: B # E: Incompatible types in assignment (expression has type "A", variable has type "B")
927 class B: pass
928 [case testConstructor]
929 class A:
930 def __init__(self, x: 'B') -> None: pass
931 class B: pass
932
933 a = A(B()) # type: A
934 aa = A(object()) # type: A # E: Argument 1 to "A" has incompatible type "object"; expected "B"
935 b = A(B()) # type: B # E: Incompatible types in assignment (expression has type "A", variable has type "B")
936
937 [case testConstructorWithTwoArguments]
938 class A:
939 def __init__(self, x: 'B', y: 'C') -> None: pass
940 class B: pass
941 class C(B): pass
942
943 a = A(C(), B()) # type: A # E: Argument 2 to "A" has incompatible type "B"; expected "C"
944
945 [case testInheritedConstructor]
946 class B(A): pass
947 class C: pass
948 class D: pass
949
950 b = B(C()) # type: B
951 a = B(D()) # type: A # E: Argument 1 to "B" has incompatible type "D"; expected "C"
952 class A:
953 def __init__(self, x: 'C') -> None: pass
954
955 [case testOverridingWithIncompatibleConstructor]
956 class A:
957 def __init__(self, x: 'C') -> None: pass
958 class B(A):
959 def __init__(self) -> None: pass
960 class C: pass
961
962 A() # E: Missing positional argument "x" in call to "A"
963 B(C()) # E: Too many arguments for "B"
964 A(C())
965 B()
966
967 [case testConstructorWithReturnValueType]
968 import typing
969 class A:
970 def __init__(self) -> 'A': pass
971 [out]
972 main:3: error: The return type of "__init__" must be None
973
974 [case testConstructorWithImplicitReturnValueType]
975 import typing
976 class A:
977 def __init__(self, x: int): pass
978 [out]
979
980 [case testDecoratedConstructorWithImplicitReturnValueType]
981 import typing
982 from typing import Callable
983
984 def deco(fn: Callable) -> Callable:
985 return fn
986
987 class A:
988 @deco
989 def __init__(self, x: int): pass
990 [out]
991
992 [case testOverloadedConstructorWithImplicitReturnValueType]
993 from foo import *
994 [file foo.pyi]
995 from typing import overload
996 class Foo:
997 @overload
998 def __init__(self, a: int):
999 pass
1000
1001 @overload
1002 def __init__(self, a: str):
1003 pass
1004
1005 [case testConstructorWithAnyReturnValueType]
1006 import typing
1007 from typing import Any
1008 class A:
1009 def __init__(self) -> Any: pass # E: The return type of "__init__" must be None
1010
1011 [case testDecoratedConstructorWithAnyReturnValueType]
1012 import typing
1013 from typing import Callable, Any
1014
1015 def deco(fn: Callable) -> Callable:
1016 return fn
1017
1018 class A:
1019 @deco
1020 def __init__(self) -> Any: pass # E: The return type of "__init__" must be None
1021
1022 [case testOverloadedConstructorWithAnyReturnValueType]
1023 from foo import *
1024 [file foo.pyi]
1025 from typing import overload, Any
1026 class Foo:
1027 @overload
1028 def __init__(self, a: int) -> Any: # E: The return type of "__init__" must be None
1029 pass
1030
1031 @overload
1032 def __init__(self, a: str) -> Any: # E: The return type of "__init__" must be None
1033 pass
1034
1035 [case testInitSubclassWithReturnValueType]
1036 import typing
1037 class A:
1038 def __init_subclass__(cls) -> 'A': pass
1039 [out]
1040 main:3: error: The return type of "__init_subclass__" must be None
1041
1042 [case testInitSubclassWithImplicitReturnValueType]
1043 import typing
1044 class A:
1045 def __init_subclass__(cls, x: int=1): pass
1046 [out]
1047
1048 [case testDecoratedInitSubclassWithImplicitReturnValueType]
1049 import typing
1050 from typing import Callable
1051
1052 def deco(fn: Callable) -> Callable:
1053 return fn
1054
1055 class A:
1056 @deco
1057 def __init_subclass__(cls, x: int=1): pass
1058 [out]
1059
1060 [case testOverloadedInitSubclassWithImplicitReturnValueType]
1061 from foo import *
1062 [file foo.pyi]
1063 from typing import overload
1064 class Foo:
1065 @overload
1066 def __init_subclass__(cls, a: int):
1067 pass
1068
1069 @overload
1070 def __init_subclass__(cls, a: str):
1071 pass
1072
1073 [case testInitSubclassWithAnyReturnValueType]
1074 import typing
1075 from typing import Any
1076 class A:
1077 def __init_subclass__(cls) -> Any: pass # E: The return type of "__init_subclass__" must be None
1078
1079 [case testDecoratedInitSubclassWithAnyReturnValueType]
1080 import typing
1081 from typing import Callable, Any
1082
1083 def deco(fn: Callable) -> Callable:
1084 return fn
1085
1086 class A:
1087 @deco
1088 def __init_subclass__(cls) -> Any: pass # E: The return type of "__init_subclass__" must be None
1089 [out]
1090
1091 [case testOverloadedInitSubclassWithAnyReturnValueType]
1092 from foo import *
1093 [file foo.pyi]
1094 from typing import overload, Any
1095 class Foo:
1096 @overload
1097 def __init_subclass__(cls, a: int) -> Any: # E: The return type of "__init_subclass__" must be None
1098 pass
1099
1100 @overload
1101 def __init_subclass__(cls, a: str) -> Any: # E: The return type of "__init_subclass__" must be None
1102 pass
1103
1104 [case testGlobalFunctionInitWithReturnType]
1105 class A: pass
1106 class B: pass
1107 def __init__() -> 'A': pass
1108
1109 a = __init__() # type: A
1110 b = __init__() # type: B # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1111 [case testAccessingInit]
1112 from typing import Any, cast
1113 class A:
1114 def __init__(self, a: 'A') -> None: pass
1115 a: A
1116 a.__init__(a) # E: Accessing "__init__" on an instance is unsound, since instance.__init__ could be from an incompatible subclass
1117 (cast(Any, a)).__init__(a)
1118
1119 [case testDeepInheritanceHierarchy]
1120 class A: pass
1121 class B(A): pass
1122 class C(B): pass
1123 class D(C): pass
1124 class D2(C): pass
1125
1126 d = C() # type: D # E: Incompatible types in assignment (expression has type "C", variable has type "D")
1127 if int():
1128 d = B() # E: Incompatible types in assignment (expression has type "B", variable has type "D")
1129 if int():
1130 d = A() # E: Incompatible types in assignment (expression has type "A", variable has type "D")
1131 if int():
1132 d = D2() # E: Incompatible types in assignment (expression has type "D2", variable has type "D")
1133 a = D() # type: A
1134 if int():
1135 a = D2()
1136 b = D() # type: B
1137 if int():
1138 b = D2()
1139
1140 [case testConstructorJoinsWithCustomMetaclass]
1141 from typing import TypeVar
1142 import abc
1143
1144 def func() -> None: pass
1145 class NormalClass: pass
1146 class WithMetaclass(metaclass=abc.ABCMeta): pass
1147
1148 T = TypeVar('T')
1149 def join(x: T, y: T) -> T: pass
1150
1151 f1 = join(func, WithMetaclass)
1152 reveal_type(f1()) # N: Revealed type is "__main__.WithMetaclass | None"
1153
1154 f2 = join(WithMetaclass, func)
1155 reveal_type(f2()) # N: Revealed type is "__main__.WithMetaclass | None"
1156
1157 -- Attribute access in class body
1158 -- ------------------------------
1159
1160
1161 [case testDataAttributeRefInClassBody]
1162 import typing
1163 class B: pass
1164 class A:
1165 x = B()
1166 y = x
1167 b = x # type: B
1168 if int():
1169 b = x
1170 c = x # type: A # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1171 if int():
1172 c = b # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1173 [out]
1174
1175 [case testMethodRefInClassBody]
1176 from typing import Callable
1177 class B: pass
1178 class A:
1179 def f(self) -> None: pass
1180 g = f
1181 h = f # type: Callable[[A], None]
1182 if int():
1183 h = f
1184 g = h
1185 ff = f # type: Callable[[B], None] # E: Incompatible types in assignment (expression has type "Callable[[A], None]", variable has type "Callable[[B], None]")
1186 if int():
1187 g = ff # E: Incompatible types in assignment (expression has type "Callable[[B], None]", variable has type "Callable[[A], None]")
1188 [out]
1189
1190
1191 -- Arbitrary statements in class body
1192 -- ----------------------------------
1193
1194
1195 [case testStatementsInClassBody]
1196 import typing
1197 class B: pass
1198 class A:
1199 for x in [A()]:
1200 y = x
1201 if int():
1202 y = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1203 if int():
1204 x = A()
1205 if int():
1206 y = A()
1207 if int():
1208 x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1209 [builtins fixtures/for.pyi]
1210 [out]
1211
1212
1213 -- Class attributes
1214 -- ----------------
1215
1216
1217 [case testAccessMethodViaClass]
1218 import typing
1219 class A:
1220 def f(self) -> None: pass
1221 A.f(A())
1222 A.f(object()) # E: Argument 1 to "f" of "A" has incompatible type "object"; expected "A"
1223 A.f() # E: Missing positional argument "self" in call to "f" of "A"
1224 A.f(None, None) # E: Too many arguments for "f" of "A" \
1225 # E: Argument 1 to "f" of "A" has incompatible type "None"; expected "A"
1226
1227 [case testAccessAttributeViaClass]
1228 import typing
1229 class B: pass
1230 class A:
1231 x: A
1232 a = A.x # type: A
1233 b = A.x # type: B # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1234
1235 [case testAccessingUndefinedAttributeViaClass]
1236 import typing
1237 class A: pass
1238 A.x # E: "type[A]" has no attribute "x"
1239
1240 [case testAccessingUndefinedAttributeViaClassWithOverloadedInit]
1241 from foo import *
1242 [file foo.pyi]
1243 from typing import overload
1244 class A:
1245 @overload
1246 def __init__(self): pass
1247 @overload
1248 def __init__(self, x): pass
1249 A.x # E: "type[A]" has no attribute "x"
1250
1251 [case testAccessMethodOfClassWithOverloadedInit]
1252 from foo import *
1253 [file foo.pyi]
1254 from typing import overload, Any
1255 class A:
1256 @overload
1257 def __init__(self) -> None: pass
1258 @overload
1259 def __init__(self, x: Any) -> None: pass
1260 def f(self) -> None: pass
1261 A.f(A())
1262 A.f() # E: Missing positional argument "self" in call to "f" of "A"
1263
1264 [case testAssignmentToClassDataAttribute]
1265 import typing
1266 class B: pass
1267 class A:
1268 x: B
1269 A.x = B()
1270 A.x = object() # E: Incompatible types in assignment (expression has type "object", variable has type "B")
1271
1272 [case testAssignmentToInferredClassDataAttribute]
1273 import typing
1274 class B: pass
1275 class A:
1276 x = B()
1277 A.x = B()
1278 A.x = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1279
1280 [case testInitMethodUnbound]
1281
1282 class B: pass
1283 class A:
1284 def __init__(self, b: B) -> None: pass
1285 a: A
1286 b: B
1287 A.__init__(a, b)
1288 A.__init__(b, b) # E: Argument 1 to "__init__" of "A" has incompatible type "B"; expected "A"
1289 A.__init__(a, a) # E: Argument 2 to "__init__" of "A" has incompatible type "A"; expected "B"
1290
1291 [case testAssignToMethodViaClass]
1292 import typing
1293 class A:
1294 def f(self): pass
1295 A.f = None # E: Cannot assign to a method \
1296 # E: Incompatible types in assignment (expression has type "None", variable has type "Callable[[A], Any]")
1297
1298 [case testAssignToNestedClassViaClass]
1299 import typing
1300 class A:
1301 class B: pass
1302 A.B = None # E: Cannot assign to a type \
1303 # E: Incompatible types in assignment (expression has type "None", variable has type "type[B]")
1304 [targets __main__]
1305
1306 [case testAccessingClassAttributeWithTypeInferenceIssue]
1307 x = C.x # E: Cannot determine type of "x" # E: Name "C" is used before definition
1308 def f() -> int: return 1
1309 class C:
1310 x = f()
1311 [builtins fixtures/list.pyi]
1312
1313 [case testAccessingClassAttributeWithTypeInferenceIssue2]
1314 class C:
1315 x = []
1316 x = C.x
1317 [builtins fixtures/list.pyi]
1318 [out]
1319 main:2: error: Need type annotation for "x" (hint: "x: list[<type>] = ...")
1320
1321 [case testAccessingGenericClassAttribute]
1322 from typing import Generic, TypeVar
1323 T = TypeVar('T')
1324 class A(Generic[T]):
1325 x: T
1326 A.x # E: Access to generic instance variables via class is ambiguous
1327 A[int].x # E: Access to generic instance variables via class is ambiguous
1328 [targets __main__]
1329
1330 [case testAccessingNestedGenericClassAttribute]
1331 from typing import Generic, List, TypeVar, Union
1332 T = TypeVar('T')
1333 U = TypeVar('U')
1334 class A(Generic[T, U]):
1335 x: Union[T, List[U]]
1336 A.x # E: Access to generic instance variables via class is ambiguous
1337 A[int, int].x # E: Access to generic instance variables via class is ambiguous
1338 [builtins fixtures/list.pyi]
1339
1340
1341 -- Nested classes
1342 -- --------------
1343
1344
1345 [case testClassWithinFunction]
1346 def f() -> None:
1347 class A:
1348 def g(self) -> None: pass
1349 a: A
1350 a.g()
1351 a.g(a) # E: Too many arguments for "g" of "A"
1352 [targets __main__, __main__.f]
1353
1354 [case testGenericClassWithinFunction]
1355 from typing import TypeVar
1356
1357 def test() -> None:
1358 T = TypeVar('T', bound='Foo')
1359 class Foo:
1360 def returns_int(self) -> int:
1361 return 0
1362
1363 def bar(self, foo: T) -> T:
1364 x: T = foo
1365 reveal_type(x) # N: Revealed type is "T`-1"
1366 reveal_type(x.returns_int()) # N: Revealed type is "builtins.int"
1367 return foo
1368 reveal_type(Foo.bar) # N: Revealed type is "def [T <: __main__.Foo@5] (self: __main__.Foo@5, foo: T`1) -> T`1"
1369
1370 [case testGenericClassWithInvalidTypevarUseWithinFunction]
1371 from typing import TypeVar
1372
1373 def test() -> None:
1374 T = TypeVar('T', bound='Foo')
1375 class Foo:
1376 invalid: T # E: Type variable "T" is unbound \
1377 # N: (Hint: Use "Generic[T]" or "Protocol[T]" base class to bind "T" inside a class) \
1378 # N: (Hint: Use "T" in function signature to bind "T" inside a function)
1379
1380 def bar(self, foo: T) -> T:
1381 pass
1382
1383 [case testConstructNestedClass]
1384 import typing
1385 class A:
1386 class B: pass
1387 b = B()
1388 if int():
1389 b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1390 if int():
1391 b = B(b) # E: Too many arguments for "B"
1392 [out]
1393
1394 [case testConstructNestedClassWithCustomInit]
1395 import typing
1396 class A:
1397 def f(self) -> None:
1398 class B:
1399 def __init__(self, a: 'A') -> None: pass
1400 b = B(A())
1401 if int():
1402 b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1403 b = B() # E: Missing positional argument "a" in call to "B"
1404 [out]
1405
1406 [case testDeclareVariableWithNestedClassType]
1407
1408 def f() -> None:
1409 class A: pass
1410 a: A
1411 if int():
1412 a = A()
1413 a = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
1414 [out]
1415
1416 [case testExternalReferenceToClassWithinClass]
1417 class A:
1418 class B: pass
1419 b: A.B
1420 if int():
1421 b = A.B()
1422 if int():
1423 b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1424 if int():
1425 b = A.B(b) # E: Too many arguments for "B"
1426
1427 [case testAliasNestedClass]
1428 class Outer:
1429 class Inner:
1430 def make_int(self) -> int: return 1
1431 reveal_type(Inner().make_int) # N: Revealed type is "def () -> builtins.int"
1432 some_int = Inner().make_int()
1433
1434 reveal_type(Outer.Inner.make_int) # N: Revealed type is "def (self: __main__.Outer.Inner) -> builtins.int"
1435 reveal_type(Outer().some_int) # N: Revealed type is "builtins.int"
1436 Bar = Outer.Inner
1437 reveal_type(Bar.make_int) # N: Revealed type is "def (self: __main__.Outer.Inner) -> builtins.int"
1438 x = Bar() # type: Bar
1439 def produce() -> Bar:
1440 reveal_type(Bar().make_int) # N: Revealed type is "def () -> builtins.int"
1441 return Bar()
1442
1443 [case testInnerClassPropertyAccess]
1444 class Foo:
1445 class Meta:
1446 name = 'Bar'
1447 meta = Meta
1448
1449 reveal_type(Foo.Meta) # N: Revealed type is "def () -> __main__.Foo.Meta"
1450 reveal_type(Foo.meta) # N: Revealed type is "def () -> __main__.Foo.Meta"
1451 reveal_type(Foo.Meta.name) # N: Revealed type is "builtins.str"
1452 reveal_type(Foo.meta.name) # N: Revealed type is "builtins.str"
1453 reveal_type(Foo().Meta) # N: Revealed type is "def () -> __main__.Foo.Meta"
1454 reveal_type(Foo().meta) # N: Revealed type is "def () -> __main__.Foo.Meta"
1455 reveal_type(Foo().meta.name) # N: Revealed type is "builtins.str"
1456 reveal_type(Foo().Meta.name) # N: Revealed type is "builtins.str"
1457
1458 -- Declaring attribute type in method
1459 -- ----------------------------------
1460
1461
1462 [case testDeclareAttributeTypeInInit]
1463
1464 class A:
1465 def __init__(self):
1466 self.x: int # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs
1467 a: A
1468 a.x = 1
1469 a.x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
1470
1471 [case testAccessAttributeDeclaredInInitBeforeDeclaration]
1472
1473 a: A
1474 a.x = 1
1475 a.x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
1476 class A:
1477 def __init__(self):
1478 self.x: int # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs
1479
1480
1481 -- Special cases
1482 -- -------------
1483
1484
1485 [case testMultipleClassDefinition]
1486 class A: pass
1487 class A: pass # E: Name "A" already defined on line 1
1488 A()
1489 [case testDocstringInClass]
1490 import typing
1491 class A:
1492 """Foo"""
1493 class B:
1494 'x'
1495 y = B()
1496 [builtins fixtures/primitives.pyi]
1497
1498 [case testErrorMessageInFunctionNestedWithinMethod]
1499 import typing
1500 class A:
1501 def f(self) -> None:
1502 def g() -> None:
1503 "" + 1 # E: Unsupported operand types for + ("str" and "int")
1504 "" + 1 # E: Unsupported operand types for + ("str" and "int")
1505 [builtins fixtures/primitives.pyi]
1506
1507 -- Static methods
1508 -- --------------
1509
1510
1511 [case testSimpleStaticMethod]
1512 import typing
1513 class A:
1514 @staticmethod
1515 def f(x: int) -> None: pass
1516 A.f(1)
1517 A().f(1)
1518 A.f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int"
1519 A().f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int"
1520 [builtins fixtures/staticmethod.pyi]
1521
1522 [case testBuiltinStaticMethod]
1523 import typing
1524 int.from_bytes(b'', '')
1525 int.from_bytes('', '') # E: Argument 1 to "from_bytes" of "int" has incompatible type "str"; expected "bytes"
1526 [builtins fixtures/staticmethod.pyi]
1527
1528 [case testAssignStaticMethodOnInstance]
1529 import typing
1530 class A:
1531 @staticmethod
1532 def f(x: int) -> None: pass
1533 A().f = A.f # E: Cannot assign to a method
1534 [builtins fixtures/staticmethod.pyi]
1535
1536
1537 -- Class methods
1538 -- -------------
1539
1540
1541 [case testSimpleClassMethod]
1542 import typing
1543 class A:
1544 @classmethod
1545 def f(cls, x: int) -> None: pass
1546 A.f(1)
1547 A().f(1)
1548 A.f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int"
1549 A().f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int"
1550 [builtins fixtures/classmethod.pyi]
1551 [targets __main__, __main__.A.f]
1552
1553 [case testBuiltinClassMethod]
1554 import typing
1555 int.from_bytes(b'', '')
1556 int.from_bytes('', '') # E: Argument 1 to "from_bytes" of "int" has incompatible type "str"; expected "bytes"
1557 [builtins fixtures/classmethod.pyi]
1558
1559 [case testAssignClassMethodOnClass]
1560 import typing
1561 class A:
1562 @classmethod
1563 def f(cls, x: int) -> None: pass
1564 A.f = A.f # E: Cannot assign to a method
1565 [builtins fixtures/classmethod.pyi]
1566
1567 [case testAssignClassMethodOnInstance]
1568 import typing
1569 class A:
1570 @classmethod
1571 def f(cls, x: int) -> None: pass
1572 A().f = A.f # E: Cannot assign to a method
1573 [builtins fixtures/classmethod.pyi]
1574
1575 [case testClassMethodCalledInClassMethod]
1576 import typing
1577 class C:
1578 @classmethod
1579 def foo(cls) -> None: pass
1580 @classmethod
1581 def bar(cls) -> None:
1582 cls()
1583 cls(1) # E: Too many arguments for "C"
1584 cls.bar()
1585 cls.bar(1) # E: Too many arguments for "bar" of "C"
1586 cls.bozo() # E: "type[C]" has no attribute "bozo"
1587 [builtins fixtures/classmethod.pyi]
1588 [out]
1589
1590 [case testClassMethodCalledOnClass]
1591 import typing
1592 class C:
1593 @classmethod
1594 def foo(cls) -> None: pass
1595 C.foo()
1596 C.foo(1) # E: Too many arguments for "foo" of "C"
1597 C.bozo() # E: "type[C]" has no attribute "bozo"
1598 [builtins fixtures/classmethod.pyi]
1599
1600 [case testClassMethodCalledOnInstance]
1601 import typing
1602 class C:
1603 @classmethod
1604 def foo(cls) -> None: pass
1605 C().foo()
1606 C().foo(1) # E: Too many arguments for "foo" of "C"
1607 C.bozo() # E: "type[C]" has no attribute "bozo"
1608 [builtins fixtures/classmethod.pyi]
1609
1610 [case testClassMethodMayCallAbstractMethod]
1611 from abc import abstractmethod
1612 import typing
1613 class C:
1614 @classmethod
1615 def foo(cls) -> None:
1616 cls().bar()
1617 @abstractmethod
1618 def bar(self) -> None:
1619 pass
1620 [builtins fixtures/classmethod.pyi]
1621
1622 [case testClassMethodSubclassing]
1623 class A:
1624 @classmethod
1625 def f(cls) -> None: pass
1626
1627 def g(self) -> None: pass
1628
1629 class B(A):
1630 def f(self) -> None: pass # Fail
1631
1632 @classmethod
1633 def g(cls) -> None: pass
1634
1635 class C(A):
1636 @staticmethod
1637 def f() -> None: pass
1638 [builtins fixtures/classmethod.pyi]
1639 [out]
1640 main:8: error: Signature of "f" incompatible with supertype "A"
1641 main:8: note: Superclass:
1642 main:8: note: @classmethod
1643 main:8: note: def f(cls) -> None
1644 main:8: note: Subclass:
1645 main:8: note: def f(self) -> None
1646
1647 [case testClassMethodAndStaticMethod]
1648 class C:
1649 @classmethod # E: Cannot have both classmethod and staticmethod
1650 @staticmethod
1651 def foo(cls) -> None: pass
1652 [builtins fixtures/classmethod.pyi]
1653
1654 -- Properties
1655 -- ----------
1656
1657
1658 [case testAccessingReadOnlyProperty]
1659 import typing
1660 class A:
1661 @property
1662 def f(self) -> str: pass
1663 a = A()
1664 reveal_type(a.f) # N: Revealed type is "builtins.str"
1665 [builtins fixtures/property.pyi]
1666
1667 [case testAssigningToReadOnlyProperty]
1668 import typing
1669 class A:
1670 @property
1671 def f(self) -> str: pass
1672 A().f = '' # E: Property "f" defined in "A" is read-only
1673 [builtins fixtures/property.pyi]
1674
1675 [case testAssigningToInheritedReadOnlyProperty]
1676 class A:
1677 @property
1678 def f(self) -> str: pass
1679 class B(A): pass
1680 class C(A):
1681 @property
1682 def f(self) -> str: pass
1683
1684 A().f = '' # E: Property "f" defined in "A" is read-only
1685 B().f = '' # E: Property "f" defined in "A" is read-only
1686 C().f = '' # E: Property "f" defined in "C" is read-only
1687 [builtins fixtures/property.pyi]
1688
1689 [case testPropertyGetterBody]
1690 import typing
1691 class A:
1692 @property
1693 def f(self) -> str:
1694 self.x = 1
1695 self.x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
1696 return ''
1697 [builtins fixtures/property.pyi]
1698
1699 [case testPropertyNameIsChecked]
1700 class A:
1701 @property
1702 def f(self) -> str: ...
1703 @not_f.setter # E: Only supported top decorators are "@f.setter" and "@f.deleter"
1704 def f(self, val: str) -> None: ...
1705
1706 a = A()
1707 reveal_type(a.f) # N: Revealed type is "builtins.str"
1708 a.f = '' # E: Property "f" defined in "A" is read-only
1709
1710 class B:
1711 @property
1712 def f(self) -> str: ...
1713 @not_f.deleter # E: Only supported top decorators are "@f.setter" and "@f.deleter"
1714 def f(self) -> None: ...
1715
1716 class C:
1717 @property
1718 def f(self) -> str: ...
1719 @not_f.setter # E: Only supported top decorators are "@f.setter" and "@f.deleter"
1720 def f(self, val: str) -> None: ...
1721 @not_f.deleter # E: Only supported top decorators are "@f.setter" and "@f.deleter"
1722 def f(self) -> None: ...
1723 [builtins fixtures/property.pyi]
1724
1725 [case testPropertyAttributeIsChecked]
1726 class A:
1727 @property
1728 def f(self) -> str: ...
1729 @f.unknown # E: Only supported top decorators are "@f.setter" and "@f.deleter"
1730 def f(self, val: str) -> None: ...
1731 @f.bad.setter # E: Only supported top decorators are "@f.setter" and "@f.deleter"
1732 def f(self, val: str) -> None: ...
1733 @f # E: Only supported top decorators are "@f.setter" and "@f.deleter"
1734 def f(self, val: str) -> None: ...
1735 @int # E: Only supported top decorators are "@f.setter" and "@f.deleter"
1736 def f(self, val: str) -> None: ...
1737 [builtins fixtures/property.pyi]
1738
1739 [case testPropertyNameAndAttributeIsCheckedPretty]
1740 # flags: --pretty
1741 class A:
1742 @property
1743 def f(self) -> str: ...
1744 @not_f.setter
1745 def f(self, val: str) -> None: ...
1746 @not_f.deleter
1747 def f(self) -> None: ...
1748
1749 class B:
1750 @property
1751 def f(self) -> str: ...
1752 @f.unknown
1753 def f(self, val: str) -> None: ...
1754 [builtins fixtures/property.pyi]
1755 [out]
1756 main:5: error: Only supported top decorators are "@f.setter" and "@f.deleter"
1757 @not_f.setter
1758 ^~~~~~~~~~~~
1759 main:7: error: Only supported top decorators are "@f.setter" and "@f.deleter"
1760 @not_f.deleter
1761 ^~~~~~~~~~~~~
1762 main:13: error: Only supported top decorators are "@f.setter" and "@f.deleter"
1763 @f.unknown
1764 ^~~~~~~~~
1765
1766 [case testPropertyGetterDecoratorIsRejected]
1767 class A:
1768 @property
1769 def f(self) -> str: ...
1770 @f.getter # E: Only supported top decorators are "@f.setter" and "@f.deleter"
1771 def f(self, val: str) -> None: ...
1772 [builtins fixtures/property.pyi]
1773
1774 [case testDynamicallyTypedProperty]
1775 import typing
1776 class A:
1777 @property
1778 def f(self): pass
1779 a = A()
1780 a.f.xx
1781 a.f = '' # E: Property "f" defined in "A" is read-only
1782 [builtins fixtures/property.pyi]
1783
1784 [case testPropertyWithSetter]
1785 import typing
1786 class A:
1787 @property
1788 def f(self) -> int:
1789 return 1
1790 @f.setter
1791 def f(self, x: int) -> None:
1792 pass
1793 a = A()
1794 a.f = a.f
1795 a.f.x # E: "int" has no attribute "x"
1796 a.f = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
1797 a.f = 1
1798 reveal_type(a.f) # N: Revealed type is "builtins.int"
1799 [builtins fixtures/property.pyi]
1800
1801 [case testPropertyWithDeleterButNoSetter]
1802 import typing
1803 class A:
1804 @property
1805 def f(self) -> int:
1806 return 1
1807 @f.deleter
1808 def f(self, x) -> None:
1809 pass
1810 a = A()
1811 a.f = a.f # E: Property "f" defined in "A" is read-only
1812 a.f.x # E: "int" has no attribute "x"
1813 [builtins fixtures/property.pyi]
1814
1815 -- Descriptors
1816 -- -----------
1817
1818
1819 [case testAccessingNonDataDescriptor]
1820 from typing import Any
1821 class D:
1822 def __get__(self, inst: Any, own: Any) -> str: return 's'
1823 class A:
1824 f = D()
1825 a = A()
1826 reveal_type(a.f) # N: Revealed type is "builtins.str"
1827
1828 [case testSettingNonDataDescriptor]
1829 from typing import Any
1830 class D:
1831 def __get__(self, inst: Any, own: Any) -> str: return 's'
1832 class A:
1833 f = D()
1834 a = A()
1835 a.f = 'foo'
1836 a.f = D() # E: Incompatible types in assignment (expression has type "D", variable has type "str")
1837
1838 [case testSettingDataDescriptor]
1839 from typing import Any
1840 class D:
1841 def __get__(self, inst: Any, own: Any) -> str: return 's'
1842 def __set__(self, inst: Any, value: str) -> None: pass
1843 class A:
1844 f = D()
1845 a = A()
1846 a.f = ''
1847 a.f = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "str")
1848
1849 [case testSettingDescriptorWithOverloadedDunderSet1]
1850 from typing import Any, overload, Union
1851 class D:
1852 @overload
1853 def __set__(self, inst: Any, value: str) -> None: pass
1854 @overload
1855 def __set__(self, inst: Any, value: int) -> None: pass
1856 def __set__(self, inst: Any, value: Union[str, int]) -> None: pass
1857 class A:
1858 f = D()
1859 a = A()
1860 a.f = ''
1861 a.f = 1
1862 a.f = 1.5 # E
1863 [out]
1864 main:13: error: No overload variant of "__set__" of "D" matches argument types "A", "float"
1865 main:13: note: Possible overload variants:
1866 main:13: note: def __set__(self, inst: Any, value: str) -> None
1867 main:13: note: def __set__(self, inst: Any, value: int) -> None
1868
1869 [case testSettingDescriptorWithOverloadedDunderSet2]
1870 from typing import overload, Union
1871 class D:
1872 @overload
1873 def __set__(self, inst: A, value: str) -> None: pass
1874 @overload
1875 def __set__(self, inst: B, value: int) -> None: pass
1876 def __set__(self, inst: Union[A, B], value: Union[str, int]) -> None: pass
1877 class A:
1878 f = D()
1879 class B:
1880 f = D()
1881 a = A()
1882 b = B()
1883 a.f = ''
1884 b.f = 1
1885 a.f = 1 # E
1886 b.f = '' # E
1887 [out]
1888 main:16: error: No overload variant of "__set__" of "D" matches argument types "A", "int"
1889 main:16: note: Possible overload variants:
1890 main:16: note: def __set__(self, inst: A, value: str) -> None
1891 main:16: note: def __set__(self, inst: B, value: int) -> None
1892 main:17: error: No overload variant of "__set__" of "D" matches argument types "B", "str"
1893 main:17: note: Possible overload variants:
1894 main:17: note: def __set__(self, inst: A, value: str) -> None
1895 main:17: note: def __set__(self, inst: B, value: int) -> None
1896
1897 [case testReadingDescriptorWithoutDunderGet]
1898 from typing import Union, Any
1899 class D:
1900 def __set__(self, inst: Any, value: str) -> None: pass
1901 class A:
1902 f = D()
1903 def __init__(self): self.f = 's'
1904 a = A()
1905 reveal_type(a.f) # N: Revealed type is "__main__.D"
1906
1907 [case testAccessingDescriptorFromClass]
1908 from d import D, Base
1909 class A(Base):
1910 f = D()
1911 reveal_type(A.f) # N: Revealed type is "d.D"
1912 reveal_type(A().f) # N: Revealed type is "builtins.str"
1913 [file d.pyi]
1914 from typing import TypeVar, Type, Generic, overload
1915 class Base: pass
1916 class D:
1917 def __init__(self) -> None: pass
1918 @overload
1919 def __get__(self, inst: None, own: Type[Base]) -> D: pass
1920 @overload
1921 def __get__(self, inst: Base, own: Type[Base]) -> str: pass
1922 [builtins fixtures/bool.pyi]
1923
1924 [case testAccessingDescriptorFromClassWrongBase]
1925 from d import D, Base
1926 class A:
1927 f = D()
1928 reveal_type(A.f)
1929 reveal_type(A().f)
1930 [file d.pyi]
1931 from typing import TypeVar, Type, Generic, overload
1932 class Base: pass
1933 class D:
1934 def __init__(self) -> None: pass
1935 @overload
1936 def __get__(self, inst: None, own: Type[Base]) -> D: pass
1937 @overload
1938 def __get__(self, inst: Base, own: Type[Base]) -> str: pass
1939 [builtins fixtures/bool.pyi]
1940 [out]
1941 main:4: error: Argument 2 to "__get__" of "D" has incompatible type "type[A]"; expected "type[Base]"
1942 main:4: note: Revealed type is "d.D"
1943 main:5: error: No overload variant of "__get__" of "D" matches argument types "A", "type[A]"
1944 main:5: note: Possible overload variants:
1945 main:5: note: def __get__(self, inst: None, own: type[Base]) -> D
1946 main:5: note: def __get__(self, inst: Base, own: type[Base]) -> str
1947 main:5: note: Revealed type is "Any"
1948
1949 [case testAccessingGenericNonDataDescriptor]
1950 from typing import TypeVar, Type, Generic, Any
1951 V = TypeVar('V')
1952 class D(Generic[V]):
1953 def __init__(self, v: V) -> None: self.v = v
1954 def __get__(self, inst: Any, own: Type) -> V: return self.v
1955 class A:
1956 f = D(10)
1957 g = D('10')
1958 a = A()
1959 reveal_type(a.f) # N: Revealed type is "builtins.int"
1960 reveal_type(a.g) # N: Revealed type is "builtins.str"
1961
1962 [case testSettingGenericDataDescriptor]
1963 from typing import TypeVar, Type, Generic, Any
1964 V = TypeVar('V')
1965 class D(Generic[V]):
1966 def __init__(self, v: V) -> None: self.v = v
1967 def __get__(self, inst: Any, own: Type) -> V: return self.v
1968 def __set__(self, inst: Any, v: V) -> None: pass
1969 class A:
1970 f = D(10)
1971 g = D('10')
1972 a = A()
1973 a.f = 1
1974 a.f = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
1975 a.g = ''
1976 a.g = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "str")
1977
1978 [case testAccessingGenericDescriptorFromClass]
1979 from d import D
1980 class A:
1981 f = D(10) # type: D[A, int]
1982 g = D('10') # type: D[A, str]
1983 reveal_type(A.f) # N: Revealed type is "d.D[__main__.A, builtins.int]"
1984 reveal_type(A.g) # N: Revealed type is "d.D[__main__.A, builtins.str]"
1985 reveal_type(A().f) # N: Revealed type is "builtins.int"
1986 reveal_type(A().g) # N: Revealed type is "builtins.str"
1987 [file d.pyi]
1988 from typing import TypeVar, Type, Generic, overload
1989 T = TypeVar('T')
1990 V = TypeVar('V')
1991 class D(Generic[T, V]):
1992 def __init__(self, v: V) -> None: pass
1993 @overload
1994 def __get__(self, inst: None, own: Type[T]) -> 'D[T, V]': pass
1995 @overload
1996 def __get__(self, inst: T, own: Type[T]) -> V: pass
1997 [builtins fixtures/bool.pyi]
1998
1999 [case testAccessingGenericDescriptorFromInferredClass]
2000 from typing import Type
2001 from d import D
2002 class A:
2003 f = D(10) # type: D[A, int]
2004 g = D('10') # type: D[A, str]
2005 def f(some_class: Type[A]):
2006 reveal_type(some_class.f)
2007 reveal_type(some_class.g)
2008 [file d.pyi]
2009 from typing import TypeVar, Type, Generic, overload
2010 T = TypeVar('T')
2011 V = TypeVar('V')
2012 class D(Generic[T, V]):
2013 def __init__(self, v: V) -> None: pass
2014 @overload
2015 def __get__(self, inst: None, own: Type[T]) -> 'D[T, V]': pass
2016 @overload
2017 def __get__(self, inst: T, own: Type[T]) -> V: pass
2018 [builtins fixtures/bool.pyi]
2019 [out]
2020 main:7: note: Revealed type is "d.D[__main__.A, builtins.int]"
2021 main:8: note: Revealed type is "d.D[__main__.A, builtins.str]"
2022
2023 [case testAccessingGenericDescriptorFromClassBadOverload]
2024 from d import D
2025 class A:
2026 f = D(10) # type: D[A, int]
2027 reveal_type(A.f)
2028 [file d.pyi]
2029 from typing import TypeVar, Type, Generic, overload
2030 T = TypeVar('T')
2031 V = TypeVar('V')
2032 class D(Generic[T, V]):
2033 def __init__(self, v: V) -> None: pass
2034 @overload
2035 def __get__(self, inst: None, own: None) -> 'D[T, V]': pass
2036 @overload
2037 def __get__(self, inst: T, own: Type[T]) -> V: pass
2038 [builtins fixtures/bool.pyi]
2039 [out]
2040 main:4: error: No overload variant of "__get__" of "D" matches argument types "None", "type[A]"
2041 main:4: note: Possible overload variants:
2042 main:4: note: def __get__(self, inst: None, own: None) -> D[A, int]
2043 main:4: note: def __get__(self, inst: A, own: type[A]) -> int
2044 main:4: note: Revealed type is "Any"
2045
2046 [case testAccessingNonDataDescriptorSubclass]
2047 from typing import Any
2048 class C:
2049 def __get__(self, inst: Any, own: Any) -> str: return 's'
2050 class D(C): pass
2051 class A:
2052 f = D()
2053 a = A()
2054 reveal_type(a.f) # N: Revealed type is "builtins.str"
2055
2056 [case testSettingDataDescriptorSubclass]
2057 from typing import Any
2058 class C:
2059 def __get__(self, inst: Any, own: Any) -> str: return 's'
2060 def __set__(self, inst: Any, v: str) -> None: pass
2061 class D(C): pass
2062 class A:
2063 f = D()
2064 a = A()
2065 a.f = ''
2066 a.f = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "str")
2067
2068 [case testReadingDescriptorSubclassWithoutDunderGet]
2069 from typing import Union, Any
2070 class C:
2071 def __set__(self, inst: Any, v: str) -> None: pass
2072 class D(C): pass
2073 class A:
2074 f = D()
2075 def __init__(self): self.f = 's'
2076 a = A()
2077 reveal_type(a.f) # N: Revealed type is "__main__.D"
2078
2079 [case testAccessingGenericNonDataDescriptorSubclass]
2080 from typing import TypeVar, Type, Generic, Any
2081 V = TypeVar('V')
2082 class C(Generic[V]):
2083 def __init__(self, v: V) -> None: self.v = v
2084 def __get__(self, inst: Any, own: Type) -> V: return self.v
2085 class D(C[V], Generic[V]): pass
2086 class A:
2087 f = D(10)
2088 g = D('10')
2089 a = A()
2090 reveal_type(a.f) # N: Revealed type is "builtins.int"
2091 reveal_type(a.g) # N: Revealed type is "builtins.str"
2092
2093 [case testSettingGenericDataDescriptorSubclass]
2094 from typing import TypeVar, Type, Generic
2095 T = TypeVar('T')
2096 V = TypeVar('V')
2097 class C(Generic[T, V]):
2098 def __init__(self, v: V) -> None: self.v = v
2099 def __get__(self, inst: T, own: Type[T]) -> V: return self.v
2100 def __set__(self, inst: T, v: V) -> None: pass
2101 class D(C[T, V], Generic[T, V]): pass
2102 class A:
2103 f = D(10) # type: D[A, int]
2104 g = D('10') # type: D[A, str]
2105 a = A()
2106 a.f = 1
2107 a.f = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
2108 a.g = ''
2109 a.g = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "str")
2110
2111 [case testSetDescriptorOnClass]
2112 from typing import TypeVar, Type, Generic
2113 T = TypeVar('T')
2114 V = TypeVar('V')
2115 class D(Generic[T, V]):
2116 def __init__(self, v: V) -> None: self.v = v
2117 def __get__(self, inst: T, own: Type[T]) -> V: return self.v
2118 def __set__(self, inst: T, v: V) -> None: pass
2119 class A:
2120 f = D(10) # type: D[A, int]
2121 A.f = D(20)
2122 A.f = D('some string') # E: Argument 1 to "D" has incompatible type "str"; expected "int"
2123
2124 [case testSetDescriptorOnInferredClass]
2125 from typing import TypeVar, Type, Generic, Any
2126 V = TypeVar('V')
2127 class D(Generic[V]):
2128 def __init__(self, v: V) -> None: self.v = v
2129 def __get__(self, inst: Any, own: Type) -> V: return self.v
2130 def __set__(self, inst: Any, v: V) -> None: pass
2131 class A:
2132 f = D(10)
2133 def f(some_class: Type[A]):
2134 A.f = D(20)
2135 A.f = D('some string')
2136 [out]
2137 main:11: error: Argument 1 to "D" has incompatible type "str"; expected "int"
2138
2139 [case testDescriptorUncallableDunderSet]
2140 class D:
2141 __set__ = 's'
2142 class A:
2143 f = D()
2144 A().f = 'x' # E: __main__.D.__set__ is not callable
2145
2146 [case testDescriptorDunderSetTooFewArgs]
2147 class D:
2148 def __set__(self, inst): pass
2149 class A:
2150 f = D()
2151 A().f = 'x' # E: Too many arguments for "__set__"
2152
2153 [case testDescriptorDunderSetTooManyArgs]
2154 class D:
2155 def __set__(self, inst, v, other): pass
2156 class A:
2157 f = D()
2158 A().f = 'x' # E: Too few arguments for "__set__"
2159
2160 [case testDescriptorDunderSetWrongArgTypes]
2161 class D:
2162 def __set__(self, inst: str, v:str) -> None: pass
2163 class A:
2164 f = D()
2165 A().f = 'x' # E: Argument 1 to "__set__" of "D" has incompatible type "A"; expected "str"
2166
2167 [case testDescriptorUncallableDunderGet]
2168 class D:
2169 __get__ = 's'
2170 class A:
2171 f = D()
2172 A().f # E: __main__.D.__get__ is not callable
2173
2174 [case testDescriptorDunderGetTooFewArgs]
2175 class D:
2176 def __get__(self, inst): pass
2177 class A:
2178 f = D()
2179 A().f # E: Too many arguments for "__get__"
2180
2181 [case testDescriptorDunderGetTooManyArgs]
2182 class D:
2183 def __get__(self, inst, own, other): pass
2184 class A:
2185 f = D()
2186 A().f = 'x' # E: Too few arguments for "__get__"
2187
2188 [case testDescriptorDunderGetWrongArgTypeForInstance]
2189 from typing import Any
2190 class D:
2191 def __get__(self, inst: str, own: Any) -> Any: pass
2192 class A:
2193 f = D()
2194 A().f # E: Argument 1 to "__get__" of "D" has incompatible type "A"; expected "str"
2195
2196 [case testDescriptorDunderGetWrongArgTypeForOwner]
2197 from typing import Any
2198 class D:
2199 def __get__(self, inst: Any, own: str) -> Any: pass
2200 class A:
2201 f = D()
2202 A().f # E: Argument 2 to "__get__" of "D" has incompatible type "type[A]"; expected "str"
2203
2204 [case testDescriptorGetSetDifferentTypes]
2205 from typing import Any
2206 class D:
2207 def __get__(self, inst: Any, own: Any) -> str: return 's'
2208 def __set__(self, inst: Any, v: int) -> None: pass
2209 class A:
2210 f = D()
2211 a = A()
2212 a.f = 1
2213 reveal_type(a.f) # N: Revealed type is "builtins.str"
2214
2215 [case testDescriptorGetUnion]
2216 from typing import Any, Union
2217 class String:
2218 def __get__(self, inst: Any, owner: Any) -> str:
2219 return ''
2220
2221 class A:
2222 attr: str
2223
2224 class B:
2225 attr = String()
2226
2227 def foo(x: Union[A, B]) -> None:
2228 reveal_type(x.attr) # N: Revealed type is "builtins.str"
2229
2230 [case testDescriptorGetUnionRestricted]
2231 from typing import Any, Union
2232
2233 class getter:
2234 def __get__(self, instance: X1, owner: Any) -> str: ...
2235
2236 class X1:
2237 prop = getter()
2238
2239 class X2:
2240 prop: str
2241
2242 def foo(x: Union[X1, X2]) -> None:
2243 reveal_type(x.prop) # N: Revealed type is "builtins.str"
2244
2245 [case testDescriptorGetUnionType]
2246 from typing import Any, Union, Type, overload
2247
2248 class getter:
2249 @overload
2250 def __get__(self, instance: None, owner: Any) -> getter: ...
2251 @overload
2252 def __get__(self, instance: object, owner: Any) -> str: ...
2253 def __get__(self, instance, owner):
2254 ...
2255
2256 class X1:
2257 prop = getter()
2258 class X2:
2259 prop = getter()
2260
2261 def foo(x: Type[Union[X1, X2]]) -> None:
2262 reveal_type(x.prop) # N: Revealed type is "__main__.getter"
2263
2264
2265 -- _promote decorators
2266 -- -------------------
2267
2268
2269 [case testSimpleDucktypeDecorator]
2270 from typing import _promote
2271 class A: pass
2272 @_promote(A)
2273 class B: pass
2274 a: A
2275 b: B
2276 if int():
2277 b = a # E: Incompatible types in assignment (expression has type "A", variable has type "B")
2278 a = b
2279 [typing fixtures/typing-medium.pyi]
2280
2281 [case testDucktypeTransitivityDecorator]
2282 from typing import _promote
2283 class A: pass
2284 @_promote(A)
2285 class B: pass
2286 @_promote(B)
2287 class C: pass
2288 a: A
2289 c: C
2290 if int():
2291 c = a # E: Incompatible types in assignment (expression has type "A", variable has type "C")
2292 a = c
2293 [typing fixtures/typing-medium.pyi]
2294
2295
2296 -- Hard coded type promotions
2297 -- --------------------------
2298
2299 [case testHardCodedTypePromotions]
2300 import typing
2301 def f(x: float) -> None: pass
2302 def g(x: complex) -> None: pass
2303 f(1)
2304 g(1)
2305 g(1.1)
2306 [builtins fixtures/complex.pyi]
2307
2308
2309 -- Operator methods
2310 -- ----------------
2311
2312
2313 [case testOperatorMethodOverrideIntroducingOverloading]
2314 from foo import *
2315 [file foo.pyi]
2316 from typing import overload
2317 class A:
2318 def __add__(self, x: int) -> int: pass
2319 class B(A):
2320 @overload # Fail
2321 def __add__(self, x: int) -> int: pass
2322 @overload
2323 def __add__(self, x: str) -> str: pass
2324 [out]
2325 tmp/foo.pyi:5: error: Signature of "__add__" incompatible with supertype "A"
2326 tmp/foo.pyi:5: note: Superclass:
2327 tmp/foo.pyi:5: note: def __add__(self, int, /) -> int
2328 tmp/foo.pyi:5: note: Subclass:
2329 tmp/foo.pyi:5: note: @overload
2330 tmp/foo.pyi:5: note: def __add__(self, int, /) -> int
2331 tmp/foo.pyi:5: note: @overload
2332 tmp/foo.pyi:5: note: def __add__(self, str, /) -> str
2333 tmp/foo.pyi:5: note: Overloaded operator methods can't have wider argument types in overrides
2334
2335 [case testOperatorMethodOverrideWideningArgumentType]
2336 import typing
2337 class A:
2338 def __add__(self, x: int) -> int: pass
2339 class B(A):
2340 def __add__(self, x: object) -> int: pass
2341 [out]
2342
2343 [case testOperatorMethodOverrideNarrowingReturnType]
2344 import typing
2345 class A:
2346 def __add__(self, x: int) -> 'A': pass
2347 class B(A):
2348 def __add__(self, x: int) -> 'B': pass
2349
2350 [case testOperatorMethodOverrideWithDynamicallyTyped]
2351 import typing
2352 class A:
2353 def __add__(self, x: int) -> 'A': pass
2354 class B(A):
2355 def __add__(self, x): pass
2356
2357 [case testOperatorMethodAgainstSameType]
2358 class A:
2359 def __add__(self, x: int) -> 'A':
2360 if isinstance(x, int):
2361 return A()
2362 else:
2363 return NotImplemented
2364
2365 def __radd__(self, x: 'A') -> 'A':
2366 if isinstance(x, A):
2367 return A()
2368 else:
2369 return NotImplemented
2370
2371 class B(A): pass
2372
2373 # Note: This is a runtime error. If we run x.__add__(y)
2374 # where x and y are *not* the same type, Python will not try
2375 # calling __radd__.
2376 A() + A() # E: Unsupported operand types for + ("A" and "A")
2377
2378 # Here, Python *will* call __radd__(...)
2379 reveal_type(B() + A()) # N: Revealed type is "__main__.A"
2380 reveal_type(A() + B()) # N: Revealed type is "__main__.A"
2381 [builtins fixtures/isinstance.pyi]
2382
2383 [case testBinaryOperatorMethodPositionalArgumentsOnly]
2384 class A:
2385 def __add__(self, other: int) -> int: pass
2386 def __iadd__(self, other: int) -> int: pass
2387 def __radd__(self, other: int) -> int: pass
2388
2389 reveal_type(A.__add__) # N: Revealed type is "def (__main__.A, builtins.int) -> builtins.int"
2390 reveal_type(A.__iadd__) # N: Revealed type is "def (__main__.A, builtins.int) -> builtins.int"
2391 reveal_type(A.__radd__) # N: Revealed type is "def (__main__.A, builtins.int) -> builtins.int"
2392
2393 [case testOperatorMethodOverrideWithIdenticalOverloadedType]
2394 from foo import *
2395 [file foo.pyi]
2396 from typing import overload
2397 class A:
2398 @overload
2399 def __add__(self, x: int) -> 'A': pass
2400 @overload
2401 def __add__(self, x: str) -> 'A': pass
2402 class B(A):
2403 @overload
2404 def __add__(self, x: int) -> 'A': pass
2405 @overload
2406 def __add__(self, x: str) -> 'A': pass
2407
2408 [case testOverloadedOperatorMethodOverrideWithDynamicallyTypedMethod]
2409 from foo import *
2410 [file foo.pyi]
2411 from typing import overload, Any
2412 class A:
2413 @overload
2414 def __add__(self, x: int) -> 'A': pass
2415 @overload
2416 def __add__(self, x: str) -> 'A': pass
2417 class B(A):
2418 def __add__(self, x): pass
2419 class C(A):
2420 def __add__(self, x: Any) -> A: pass
2421
2422 [case testOverloadedOperatorMethodOverrideWithNewItem]
2423 from foo import *
2424 [file foo.pyi]
2425 from typing import overload, Any
2426 class A:
2427 @overload
2428 def __add__(self, x: int) -> 'A': pass
2429 @overload
2430 def __add__(self, x: str) -> 'A': pass
2431 class B(A):
2432 @overload # Fail
2433 def __add__(self, x: int) -> A: pass
2434 @overload
2435 def __add__(self, x: str) -> A: pass
2436 @overload
2437 def __add__(self, x: type) -> A: pass
2438 [out]
2439 tmp/foo.pyi:8: error: Signature of "__add__" incompatible with supertype "A"
2440 tmp/foo.pyi:8: note: Superclass:
2441 tmp/foo.pyi:8: note: @overload
2442 tmp/foo.pyi:8: note: def __add__(self, int, /) -> A
2443 tmp/foo.pyi:8: note: @overload
2444 tmp/foo.pyi:8: note: def __add__(self, str, /) -> A
2445 tmp/foo.pyi:8: note: Subclass:
2446 tmp/foo.pyi:8: note: @overload
2447 tmp/foo.pyi:8: note: def __add__(self, int, /) -> A
2448 tmp/foo.pyi:8: note: @overload
2449 tmp/foo.pyi:8: note: def __add__(self, str, /) -> A
2450 tmp/foo.pyi:8: note: @overload
2451 tmp/foo.pyi:8: note: def __add__(self, type, /) -> A
2452 tmp/foo.pyi:8: note: Overloaded operator methods can't have wider argument types in overrides
2453
2454 [case testOverloadedOperatorMethodOverrideWithSwitchedItemOrder]
2455 from foo import *
2456 [file foo.pyi]
2457 from typing import overload, Any
2458 class A:
2459 @overload
2460 def __add__(self, x: 'B') -> 'B': pass
2461 @overload
2462 def __add__(self, x: 'A') -> 'A': pass
2463 class B(A):
2464 @overload
2465 def __add__(self, x: 'A') -> 'A': pass
2466 @overload
2467 def __add__(self, x: 'B') -> 'B': pass
2468 class C(A):
2469 @overload
2470 def __add__(self, x: 'B') -> 'B': pass
2471 @overload
2472 def __add__(self, x: 'A') -> 'A': pass
2473 [out]
2474 tmp/foo.pyi:8: error: Signature of "__add__" incompatible with supertype "A"
2475 tmp/foo.pyi:8: note: Overload variants must be defined in the same order as they are in "A"
2476 tmp/foo.pyi:11: error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
2477
2478 [case testReverseOperatorMethodArgumentType]
2479 from typing import Any
2480 class A: pass
2481 class B:
2482 def __radd__(self, x: A) -> int: pass # Error
2483 class C:
2484 def __radd__(self, x: A) -> Any: pass
2485 class D:
2486 def __radd__(self, x: A) -> object: pass
2487 [out]
2488
2489 [case testReverseOperatorMethodArgumentType2]
2490 from typing import Any, Tuple, Callable
2491 class A:
2492 def __radd__(self, x: Tuple[int, str]) -> int: pass
2493 class B:
2494 def __radd__(self, x: Callable[[], int]) -> int: pass
2495 class C:
2496 def __radd__(self, x: Any) -> int: pass
2497 [builtins fixtures/tuple.pyi]
2498 [out]
2499
2500 [case testReverseOperatorMethodInvalid]
2501 from foo import *
2502 [file foo.pyi]
2503 class A: ...
2504 class B:
2505 def __rmul__(self) -> A: ...
2506 class C:
2507 def __radd__(self, other, oops) -> int: ...
2508 [out]
2509 tmp/foo.pyi:3: error: Invalid signature "Callable[[B], A]"
2510 tmp/foo.pyi:5: error: Invalid signature "Callable[[C, Any, Any], int]"
2511
2512 [case testReverseOperatorOrderingCase1]
2513 class A:
2514 def __radd__(self, other: 'A') -> int: ...
2515
2516 # Note: Python only tries calling __add__ and never __radd__, even though it's present
2517 A() + A() # E: Unsupported left operand type for + ("A")
2518
2519 [case testReverseOperatorOrderingCase2]
2520 class A:
2521 def __lt__(self, other: object) -> bool: ...
2522
2523 # Not all operators have the above shortcut though.
2524 reveal_type(A() > A()) # N: Revealed type is "builtins.bool"
2525 reveal_type(A() < A()) # N: Revealed type is "builtins.bool"
2526 [builtins fixtures/bool.pyi]
2527
2528 [case testReverseOperatorOrderingCase3]
2529 class A:
2530 def __add__(self, other: B) -> int: ...
2531
2532 class B:
2533 def __radd__(self, other: A) -> str: ... # E: Signatures of "__radd__" of "B" and "__add__" of "A" are unsafely overlapping
2534
2535 # Normally, we try calling __add__ before __radd__
2536 reveal_type(A() + B()) # N: Revealed type is "builtins.int"
2537
2538 [case testReverseOperatorOrderingCase4]
2539 class A:
2540 def __add__(self, other: B) -> int: ...
2541
2542 class B(A):
2543 def __radd__(self, other: A) -> str: ... # E: Signatures of "__radd__" of "B" and "__add__" of "A" are unsafely overlapping
2544
2545 # However, if B is a subtype of A, we try calling __radd__ first.
2546 reveal_type(A() + B()) # N: Revealed type is "builtins.str"
2547
2548 [case testReverseOperatorOrderingCase5]
2549 # Note: these two methods are not unsafely overlapping because __radd__ is
2550 # never called -- see case 1.
2551 class A:
2552 def __add__(self, other: B) -> int: ...
2553 def __radd__(self, other: A) -> str: ...
2554
2555 class B(A): pass
2556
2557 # ...but only if B specifically defines a new __radd__.
2558 reveal_type(A() + B()) # N: Revealed type is "builtins.int"
2559
2560 [case testReverseOperatorOrderingCase6]
2561 class A:
2562 def __add__(self, other: B) -> int: ...
2563 def __radd__(self, other: A) -> str: ...
2564
2565 class B(A):
2566 # Although A.__radd__ can never be called, B.__radd__ *can* be -- so the
2567 # unsafe overlap check kicks in here.
2568 def __radd__(self, other: A) -> str: ... # E: Signatures of "__radd__" of "B" and "__add__" of "A" are unsafely overlapping
2569
2570 reveal_type(A() + B()) # N: Revealed type is "builtins.str"
2571
2572 [case testReverseOperatorOrderingCase7]
2573 class A:
2574 def __add__(self, other: B) -> int: ...
2575 def __radd__(self, other: A) -> str: ...
2576
2577 class B(A):
2578 def __radd__(self, other: A) -> str: ... # E: Signatures of "__radd__" of "B" and "__add__" of "A" are unsafely overlapping
2579
2580 class C(B): pass
2581
2582 # A refinement made by a parent also counts
2583 reveal_type(A() + C()) # N: Revealed type is "builtins.str"
2584
2585 [case testReverseOperatorWithOverloads1]
2586 from typing import overload
2587
2588 class A:
2589 def __add__(self, other: C) -> int: ...
2590
2591 class B:
2592 def __add__(self, other: C) -> int: ...
2593
2594 class C:
2595 @overload
2596 def __radd__(self, other: A) -> str: ... # E: Signatures of "__radd__" of "C" and "__add__" of "A" are unsafely overlapping
2597 @overload
2598 def __radd__(self, other: B) -> str: ... # E: Signatures of "__radd__" of "C" and "__add__" of "B" are unsafely overlapping
2599 def __radd__(self, other): pass
2600
2601 reveal_type(A() + C()) # N: Revealed type is "builtins.int"
2602 reveal_type(B() + C()) # N: Revealed type is "builtins.int"
2603
2604 [case testReverseOperatorWithOverloads2]
2605 from typing import overload, Union
2606
2607 class Num1:
2608 def __add__(self, other: Num1) -> Num1: ...
2609 def __radd__(self, other: Num1) -> Num1: ...
2610
2611 class Num2(Num1):
2612 @overload
2613 def __add__(self, other: Num2) -> Num2: ...
2614 @overload
2615 def __add__(self, other: Num1) -> Num2: ...
2616 def __add__(self, other): pass
2617
2618 @overload
2619 def __radd__(self, other: Num2) -> Num2: ...
2620 @overload
2621 def __radd__(self, other: Num1) -> Num2: ...
2622 def __radd__(self, other): pass
2623
2624 class Num3(Num1):
2625 def __add__(self, other: Union[Num1, Num3]) -> Num3: ...
2626 def __radd__(self, other: Union[Num1, Num3]) -> Num3: ...
2627
2628 reveal_type(Num1() + Num2()) # N: Revealed type is "__main__.Num2"
2629 reveal_type(Num2() + Num1()) # N: Revealed type is "__main__.Num2"
2630
2631 reveal_type(Num1() + Num3()) # N: Revealed type is "__main__.Num3"
2632 reveal_type(Num3() + Num1()) # N: Revealed type is "__main__.Num3"
2633
2634 reveal_type(Num2() + Num3()) # N: Revealed type is "__main__.Num2"
2635 reveal_type(Num3() + Num2()) # N: Revealed type is "__main__.Num3"
2636
2637 [case testReverseOperatorWithOverloads3]
2638 from typing import Union, overload
2639
2640 class A:
2641 def __mul__(self, value: A, /) -> A: ...
2642 def __rmul__(self, value: A, /) -> A: ...
2643
2644 class B:
2645 @overload
2646 def __mul__(self, other: B, /) -> B: ...
2647 @overload
2648 def __mul__(self, other: A, /) -> str: ...
2649 def __mul__(self, other: Union[B, A], /) -> Union[B, str]: pass
2650
2651 @overload
2652 def __rmul__(self, other: B, /) -> B: ...
2653 @overload
2654 def __rmul__(self, other: A, /) -> str: ...
2655 def __rmul__(self, other: Union[B, A], /) -> Union[B, str]: pass
2656
2657 [case testReverseOperatorWithOverloadsNested]
2658 from typing import Union, overload
2659
2660 class A:
2661 def __mul__(self, value: A, /) -> A: ...
2662 def __rmul__(self, value: A, /) -> A: ...
2663
2664 class B:
2665 @overload
2666 def __mul__(self, other: B, /) -> B: ...
2667 @overload
2668 def __mul__(self, other: A, /) -> str: ...
2669 def __mul__(self, other: Union[B, A], /) -> Union[B, str]: pass
2670
2671 @overload
2672 def __rmul__(self, other: B, /) -> B: ...
2673 @overload
2674 def __rmul__(self, other: A, /) -> str: ...
2675 def __rmul__(self, other: Union[B, A], /) -> Union[B, str]:
2676 class A1:
2677 def __add__(self, other: C1) -> int: ...
2678
2679 class B1:
2680 def __add__(self, other: C1) -> int: ...
2681
2682 class C1:
2683 @overload
2684 def __radd__(self, other: A1) -> str: ... # E: Signatures of "__radd__" of "C1" and "__add__" of "A1" are unsafely overlapping
2685 @overload
2686 def __radd__(self, other: B1) -> str: ... # E: Signatures of "__radd__" of "C1" and "__add__" of "B1" are unsafely overlapping
2687 def __radd__(self, other): pass
2688
2689 return ""
2690
2691 [case testDivReverseOperator]
2692 # No error: __div__ has no special meaning in Python 3
2693 class A1:
2694 def __div__(self, x: B1) -> int: ...
2695 class B1:
2696 def __rdiv__(self, x: A1) -> str: ...
2697
2698 class A2:
2699 def __truediv__(self, x: B2) -> int: ...
2700 class B2:
2701 def __rtruediv__(self, x: A2) -> str: ... # E: Signatures of "__rtruediv__" of "B2" and "__truediv__" of "A2" are unsafely overlapping
2702
2703 A1() / B1() # E: Unsupported left operand type for / ("A1")
2704 reveal_type(A2() / B2()) # N: Revealed type is "builtins.int"
2705
2706 [case testReverseOperatorMethodForwardIsAny]
2707 from typing import Any
2708 def deco(f: Any) -> Any: return f
2709 class C:
2710 @deco
2711 def __add__(self, other: C) -> C: return C()
2712 def __radd__(self, other: C) -> C: return C()
2713 [out]
2714
2715 [case testReverseOperatorMethodForwardIsAny2]
2716 from typing import Any
2717 def deco(f: Any) -> Any: return f
2718 class C:
2719 __add__ = None # type: Any
2720 def __radd__(self, other: C) -> C: return C()
2721 [out]
2722
2723 [case testReverseOperatorMethodForwardIsAny3]
2724 from typing import Any
2725 def deco(f: Any) -> Any: return f
2726 class C:
2727 __add__ = 42
2728 def __radd__(self, other: C) -> C: return C()
2729 [out]
2730 main:5: error: Forward operator "__add__" is not callable
2731
2732 [case testOverloadedReverseOperatorMethodArgumentType]
2733 from foo import *
2734 [file foo.pyi]
2735 from typing import overload, Any
2736 class A:
2737 @overload
2738 def __radd__(self, x: 'A') -> str: pass
2739 @overload
2740 def __radd__(self, x: 'A') -> Any: pass # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
2741 [out]
2742
2743 [case testReverseOperatorMethodArgumentTypeAndOverloadedMethod]
2744 from foo import *
2745 [file foo.pyi]
2746 from typing import overload
2747 class A:
2748 @overload
2749 def __add__(self, x: int) -> int: pass
2750 @overload
2751 def __add__(self, x: str) -> int: pass
2752 def __radd__(self, x: 'A') -> str: pass
2753
2754 [case testReverseOperatorStar]
2755 class B:
2756 def __radd__(*self) -> int: pass
2757 def __rsub__(*self: 'B') -> int: pass
2758 [builtins fixtures/tuple.pyi]
2759
2760 [case testReverseOperatorTypeVar1]
2761 from typing import TypeVar
2762 T = TypeVar("T", bound='Real')
2763 class Real:
2764 def __add__(self, other: object) -> str: ...
2765 class Fraction(Real):
2766 def __radd__(self, other: T) -> T: ... # E: Signatures of "__radd__" of "Fraction" and "__add__" of "T" are unsafely overlapping
2767
2768 # Note: When doing A + B and if B is a subtype of A, we will always call B.__radd__(A) first
2769 # and only try A.__add__(B) second if necessary.
2770 reveal_type(Real() + Fraction()) # N: Revealed type is "__main__.Real"
2771
2772 # Note: When doing A + A, we only ever call A.__add__(A), never A.__radd__(A).
2773 reveal_type(Fraction() + Fraction()) # N: Revealed type is "builtins.str"
2774
2775 [case testReverseOperatorTypeVar2a]
2776 from typing import TypeVar
2777 T = TypeVar("T", bound='Real')
2778 class Real:
2779 def __add__(self, other: Fraction) -> str: ...
2780 class Fraction(Real):
2781 def __radd__(self, other: T) -> T: ... # E: Signatures of "__radd__" of "Fraction" and "__add__" of "T" are unsafely overlapping
2782
2783 reveal_type(Real() + Fraction()) # N: Revealed type is "__main__.Real"
2784 reveal_type(Fraction() + Fraction()) # N: Revealed type is "builtins.str"
2785
2786
2787 [case testReverseOperatorTypeVar2b]
2788 from typing import TypeVar
2789 T = TypeVar("T", "Real", "Fraction")
2790 class Real:
2791 def __add__(self, other: Fraction) -> str: ...
2792 class Fraction(Real):
2793 def __radd__(self, other: T) -> T: ... # E: Signatures of "__radd__" of "Fraction" and "__add__" of "Real" are unsafely overlapping
2794
2795 reveal_type(Real() + Fraction()) # N: Revealed type is "__main__.Real"
2796 reveal_type(Fraction() + Fraction()) # N: Revealed type is "builtins.str"
2797
2798 [case testReverseOperatorTypeVar3]
2799 from typing import TypeVar
2800 T = TypeVar("T", bound='Real')
2801 class Real:
2802 def __add__(self, other: FractionChild) -> str: ...
2803 class Fraction(Real):
2804 def __radd__(self, other: T) -> T: ... # E: Signatures of "__radd__" of "Fraction" and "__add__" of "T" are unsafely overlapping
2805 class FractionChild(Fraction): pass
2806
2807 reveal_type(Real() + Fraction()) # N: Revealed type is "__main__.Real"
2808 reveal_type(FractionChild() + Fraction()) # N: Revealed type is "__main__.FractionChild"
2809 reveal_type(FractionChild() + FractionChild()) # N: Revealed type is "builtins.str"
2810
2811 # Runtime error: we try calling __add__, it doesn't match, and we don't try __radd__ since
2812 # the LHS and the RHS are not the same.
2813 Fraction() + Fraction() # E: Unsupported operand types for + ("Fraction" and "Fraction")
2814
2815 [case testReverseOperatorTypeType]
2816 from typing import TypeVar, Type
2817 class Real(type):
2818 def __add__(self, other: FractionChild) -> str: ...
2819 class Fraction(Real):
2820 def __radd__(self, other: Type['A']) -> Real: ... # E: Signatures of "__radd__" of "Fraction" and "__add__" of "type[A]" are unsafely overlapping
2821 class FractionChild(Fraction): pass
2822
2823 class A(metaclass=Real): pass
2824
2825 [case testOperatorDoubleUnionIntFloat]
2826 from typing import Union
2827
2828 a: Union[int, float]
2829 b: int
2830 c: float
2831
2832 reveal_type(a + a) # N: Revealed type is "builtins.int | builtins.float"
2833 reveal_type(a + b) # N: Revealed type is "builtins.int | builtins.float"
2834 reveal_type(b + a) # N: Revealed type is "builtins.int | builtins.float"
2835 reveal_type(a + c) # N: Revealed type is "builtins.float"
2836 reveal_type(c + a) # N: Revealed type is "builtins.float"
2837 [builtins fixtures/ops.pyi]
2838
2839 [case testOperatorDoubleUnionStandardSubtyping]
2840 from typing import Union
2841
2842 class Parent:
2843 def __add__(self, x: Parent) -> Parent: pass
2844 def __radd__(self, x: Parent) -> Parent: pass
2845
2846 class Child(Parent):
2847 def __add__(self, x: Parent) -> Child: pass
2848 def __radd__(self, x: Parent) -> Child: pass
2849
2850 a: Union[Parent, Child]
2851 b: Parent
2852 c: Child
2853
2854 reveal_type(a + a) # N: Revealed type is "__main__.Parent"
2855 reveal_type(a + b) # N: Revealed type is "__main__.Parent"
2856 reveal_type(b + a) # N: Revealed type is "__main__.Parent"
2857 reveal_type(a + c) # N: Revealed type is "__main__.Child"
2858 reveal_type(c + a) # N: Revealed type is "__main__.Child"
2859
2860 [case testOperatorDoubleUnionNoRelationship1]
2861 from typing import Union
2862
2863 class Foo:
2864 def __add__(self, x: Foo) -> Foo: pass
2865 def __radd__(self, x: Foo) -> Foo: pass
2866
2867 class Bar:
2868 def __add__(self, x: Bar) -> Bar: pass
2869 def __radd__(self, x: Bar) -> Bar: pass
2870
2871 a: Union[Foo, Bar]
2872 b: Foo
2873 c: Bar
2874
2875 a + a # E: Unsupported operand types for + ("Foo" and "Bar") \
2876 # E: Unsupported operand types for + ("Bar" and "Foo") \
2877 # N: Both left and right operands are unions
2878
2879 a + b # E: Unsupported operand types for + ("Bar" and "Foo") \
2880 # N: Left operand is of type "Foo | Bar"
2881
2882 b + a # E: Unsupported operand types for + ("Foo" and "Bar") \
2883 # N: Right operand is of type "Foo | Bar"
2884
2885 a + c # E: Unsupported operand types for + ("Foo" and "Bar") \
2886 # N: Left operand is of type "Foo | Bar"
2887
2888 c + a # E: Unsupported operand types for + ("Bar" and "Foo") \
2889 # N: Right operand is of type "Foo | Bar"
2890
2891 [case testOperatorDoubleUnionNoRelationship2]
2892 from typing import Union
2893
2894 class Foo:
2895 def __add__(self, x: Foo) -> Foo: pass
2896 def __radd__(self, x: Foo) -> Foo: pass
2897
2898 class Bar:
2899 def __add__(self, x: Union[Foo, Bar]) -> Bar: pass
2900 def __radd__(self, x: Union[Foo, Bar]) -> Bar: pass
2901
2902 a: Union[Foo, Bar]
2903 b: Foo
2904 c: Bar
2905
2906 reveal_type(a + a) # N: Revealed type is "__main__.Foo | __main__.Bar"
2907 reveal_type(a + b) # N: Revealed type is "__main__.Foo | __main__.Bar"
2908 reveal_type(b + a) # N: Revealed type is "__main__.Foo | __main__.Bar"
2909 reveal_type(a + c) # N: Revealed type is "__main__.Bar"
2910 reveal_type(c + a) # N: Revealed type is "__main__.Bar"
2911
2912 [case testOperatorDoubleUnionNaiveAdd]
2913 from typing import Union
2914
2915 class A: pass
2916 class B: pass
2917 class C:
2918 def __radd__(self, x: A) -> int: pass
2919 class D:
2920 def __radd__(self, x: B) -> str: pass
2921
2922 x: Union[A, B]
2923 y: Union[C, D]
2924
2925 x + y # E: Unsupported operand types for + ("A" and "D") \
2926 # E: Unsupported operand types for + ("B" and "C") \
2927 # N: Both left and right operands are unions
2928
2929 [case testOperatorDoubleUnionInterwovenUnionAdd]
2930 from typing import Union
2931
2932 class Out1: pass
2933 class Out2: pass
2934 class Out3: pass
2935 class Out4: pass
2936
2937 class A:
2938 def __add__(self, x: D) -> Out1: pass
2939 class B:
2940 def __add__(self, x: C) -> Out2: pass
2941 class C:
2942 def __radd__(self, x: A) -> Out3: pass
2943 class D:
2944 def __radd__(self, x: B) -> Out4: pass
2945
2946 x: Union[A, B]
2947 y: Union[C, D]
2948
2949 reveal_type(x + y) # N: Revealed type is "__main__.Out3 | __main__.Out1 | __main__.Out2 | __main__.Out4"
2950 reveal_type(A() + y) # N: Revealed type is "__main__.Out3 | __main__.Out1"
2951 reveal_type(B() + y) # N: Revealed type is "__main__.Out2 | __main__.Out4"
2952 reveal_type(x + C()) # N: Revealed type is "__main__.Out3 | __main__.Out2"
2953 reveal_type(x + D()) # N: Revealed type is "__main__.Out1 | __main__.Out4"
2954
2955 [case testOperatorDoubleUnionDivision]
2956 from typing import Union
2957 def f(a):
2958 # type: (Union[int, float]) -> None
2959 a /= 1.1
2960 b = a / 1.1
2961 reveal_type(b) # N: Revealed type is "builtins.float"
2962 [builtins fixtures/ops.pyi]
2963
2964 [case testOperatorWithInference]
2965 from typing import TypeVar, Iterable, Union
2966
2967 T = TypeVar('T')
2968 def sum(x: Iterable[T]) -> Union[T, int]: ...
2969
2970 def len(x: Iterable[T]) -> int: ...
2971
2972 x = [1.1, 2.2, 3.3]
2973 reveal_type(sum(x)) # N: Revealed type is "builtins.float | builtins.int"
2974 reveal_type(sum(x) / len(x)) # N: Revealed type is "builtins.float | builtins.int"
2975 [builtins fixtures/floatdict.pyi]
2976
2977 [case testOperatorWithEmptyListAndSum]
2978 from typing import TypeVar, Iterable, Union, overload
2979
2980 T = TypeVar('T')
2981 S = TypeVar('S')
2982 @overload
2983 def sum(x: Iterable[T]) -> Union[T, int]: ...
2984 @overload
2985 def sum(x: Iterable[T], default: S) -> Union[T, S]: ...
2986 def sum(*args): pass
2987
2988 x = ["a", "b", "c"]
2989 reveal_type(x + sum([x, x, x], [])) # N: Revealed type is "builtins.list[builtins.str]"
2990 [builtins fixtures/floatdict.pyi]
2991
2992 [case testAbstractReverseOperatorMethod]
2993 import typing
2994 from abc import abstractmethod
2995 class A:
2996 @abstractmethod
2997 def __lt__(self, x: 'A') -> int: pass
2998 class B:
2999 @abstractmethod
3000 def __lt__(self, x: 'B') -> int: pass
3001 @abstractmethod
3002 def __gt__(self, x: 'B') -> int: pass
3003 [out]
3004
3005 [case testOperatorMethodsAndOverloadingSpecialCase]
3006 from foo import *
3007 [file foo.pyi]
3008 from typing import overload
3009 class A:
3010 @overload
3011 def __add__(self, x: 'A') -> int: pass
3012 @overload
3013 def __add__(self, x: str) -> int: pass
3014 class B:
3015 def __radd__(self, x: 'A') -> str: pass
3016 [out]
3017
3018 [case testUnsafeOverlappingWithOperatorMethodsAndOverloading2]
3019 from foo import A, B
3020 from foo import *
3021 [file foo.pyi]
3022 from typing import overload
3023 class A:
3024 def __add__(self, x: 'A') -> int: pass
3025 class B:
3026 @overload
3027 def __radd__(self, x: 'X') -> str: pass # Error
3028 @overload
3029 def __radd__(self, x: A) -> str: pass # Error
3030 class X:
3031 def __add__(self, x: B) -> int: pass
3032 [out]
3033 tmp/foo.pyi:6: error: Signatures of "__radd__" of "B" and "__add__" of "X" are unsafely overlapping
3034
3035 [case testUnsafeOverlappingNotWithAny]
3036 from typing import TypeVar
3037 class Real:
3038 def __add__(self, other) -> str: ...
3039 class Fraction(Real):
3040 def __radd__(self, other: Real) -> Real: ...
3041
3042 [case testOverlappingNormalAndInplaceOperatorMethod]
3043 import typing
3044 class A:
3045 # Incompatible (potential trouble with __radd__)
3046 def __add__(self, x: 'A') -> int: pass
3047 def __iadd__(self, x: 'B') -> int: pass
3048 class B:
3049 # Safe
3050 def __add__(self, x: 'C') -> int: pass
3051 def __iadd__(self, x: A) -> int: pass
3052 class C(A): pass
3053 [out]
3054 main:5: error: Signatures of "__iadd__" and "__add__" are incompatible
3055
3056 [case testOverloadedNormalAndInplaceOperatorMethod]
3057 from foo import *
3058 [file foo.pyi]
3059 from typing import overload
3060 class A:
3061 @overload
3062 def __add__(self, x: int) -> int: pass
3063 @overload
3064 def __add__(self, x: str) -> int: pass
3065 @overload # Error
3066 def __iadd__(self, x: int) -> int: pass
3067 @overload
3068 def __iadd__(self, x: object) -> int: pass
3069 class B:
3070 @overload
3071 def __add__(self, x: int) -> int: pass
3072 @overload
3073 def __add__(self, x: str) -> str: pass
3074 @overload
3075 def __iadd__(self, x: int) -> int: pass
3076 @overload
3077 def __iadd__(self, x: str) -> str: pass
3078 [out]
3079 tmp/foo.pyi:7: error: Signatures of "__iadd__" and "__add__" are incompatible
3080
3081 [case testIntroducingInplaceOperatorInSubclass]
3082 import typing
3083 class A:
3084 def __add__(self, x: 'A') -> 'B': pass
3085 class B(A):
3086 # __iadd__ effectively partially overrides __add__
3087 def __iadd__(self, x: 'A') -> 'A': pass # Error
3088 class C(A):
3089 def __iadd__(self, x: int) -> 'B': pass # Error
3090 class D(A):
3091 def __iadd__(self, x: 'A') -> 'B': pass
3092 [out]
3093 main:6: error: Return type "A" of "__iadd__" incompatible with return type "B" in "__add__" of supertype "A"
3094 main:8: error: Signatures of "__iadd__" and "__add__" are incompatible
3095 main:8: error: Argument 1 of "__iadd__" is incompatible with "__add__" of supertype "A"; supertype defines the argument type as "A"
3096 main:8: note: This violates the Liskov substitution principle
3097 main:8: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
3098
3099 [case testGetattribute]
3100 a: A
3101 b: B
3102 class A:
3103 def __getattribute__(self, x: str) -> A:
3104 return A()
3105 class B: pass
3106
3107 a = a.foo
3108 b = a.bar
3109 [builtins fixtures/tuple.pyi]
3110 [out]
3111 main:9: error: Incompatible types in assignment (expression has type "A", variable has type "B")
3112
3113 [case testDecoratedGetAttribute]
3114 from typing import Callable, TypeVar
3115
3116 T = TypeVar('T', bound=Callable)
3117
3118 def decorator(f: T) -> T:
3119 return f
3120
3121 def bad(f: Callable) -> Callable[..., int]:
3122 return f
3123
3124 class A:
3125 @decorator
3126 def __getattribute__(self, x: str) -> A:
3127 return A()
3128 class B:
3129 @bad # We test that type will be taken from decorated type, not node itself
3130 def __getattribute__(self, x: str) -> A:
3131 return A()
3132
3133 a: A
3134 b: B
3135
3136 a1: A = a.foo
3137 b1: B = a.bar # E: Incompatible types in assignment (expression has type "A", variable has type "B")
3138 a2: A = b.baz # E: Incompatible types in assignment (expression has type "int", variable has type "A")
3139 b2: B = b.roo # E: Incompatible types in assignment (expression has type "int", variable has type "B")
3140 [builtins fixtures/tuple.pyi]
3141
3142 [case testGetattributeSignature]
3143 class A:
3144 def __getattribute__(self, x: str) -> A: pass
3145 class B:
3146 def __getattribute__(self, x: A) -> B: pass
3147 class C:
3148 def __getattribute__(self, x: str, y: str) -> C: pass
3149 class D:
3150 def __getattribute__(self, x: str) -> None: pass
3151 [out]
3152 main:4: error: Invalid signature "Callable[[B, A], B]" for "__getattribute__"
3153 main:6: error: Invalid signature "Callable[[C, str, str], C]" for "__getattribute__"
3154
3155 [case testGetattr]
3156 a: A
3157 b: B
3158 class A:
3159 def __getattr__(self, x: str) -> A:
3160 return A()
3161 class B: pass
3162
3163 a = a.foo
3164 b = a.bar
3165 [builtins fixtures/tuple.pyi]
3166 [out]
3167 main:9: error: Incompatible types in assignment (expression has type "A", variable has type "B")
3168
3169 [case testDecoratedGetattr]
3170 from typing import Callable, TypeVar
3171
3172 T = TypeVar('T', bound=Callable)
3173
3174 def decorator(f: T) -> T:
3175 return f
3176
3177 def bad(f: Callable) -> Callable[..., int]:
3178 return f
3179
3180 class A:
3181 @decorator
3182 def __getattr__(self, x: str) -> A:
3183 return A()
3184 class B:
3185 @bad # We test that type will be taken from decorated type, not node itself
3186 def __getattr__(self, x: str) -> A:
3187 return A()
3188
3189 a: A
3190 b: B
3191
3192 a1: A = a.foo
3193 b1: B = a.bar # E: Incompatible types in assignment (expression has type "A", variable has type "B")
3194 a2: A = b.baz # E: Incompatible types in assignment (expression has type "int", variable has type "A")
3195 b2: B = b.roo # E: Incompatible types in assignment (expression has type "int", variable has type "B")
3196 [builtins fixtures/tuple.pyi]
3197
3198 [case testGetattrWithGetitem]
3199 class A:
3200 def __getattr__(self, x: str) -> 'A':
3201 return A()
3202
3203 a = A()
3204 a[0] # E: Value of type "A" is not indexable
3205
3206 [case testGetattrWithCall]
3207 class A:
3208 def __getattr__(self, x: str) -> 'A':
3209 return A()
3210
3211 a = A()
3212 a.y() # E: "A" not callable
3213
3214 [case testGetattrWithCallable]
3215 from typing import Callable, Any
3216
3217 class C:
3218 def __getattr__(self, attr: str) -> C: ...
3219
3220 def do(cd: Callable[..., Any]) -> None: ...
3221
3222 do(C()) # E: Argument 1 to "do" has incompatible type "C"; expected "Callable[..., Any]"
3223
3224 [case testGetattrWithCallableTypeVar]
3225 from typing import Callable, Any, TypeVar
3226
3227 class C:
3228 def __getattr__(self, attr: str) -> C: ...
3229
3230 T = TypeVar('T', bound=Callable[..., Any])
3231
3232 def do(cd: T) -> T: ...
3233
3234 do(C()) # E: Value of type variable "T" of "do" cannot be "C"
3235
3236 [case testNestedGetattr]
3237 def foo() -> object:
3238 def __getattr__() -> None: # no error because not in a class
3239 pass
3240 return __getattr__
3241
3242 class X:
3243 def foo(self) -> object:
3244 def __getattr__() -> None: # no error because not directly inside a class
3245 pass
3246 return __getattr__
3247
3248 [case testGetattrSignature]
3249 class A:
3250 def __getattr__(self, x: str) -> A: pass
3251 class B:
3252 def __getattr__(self, x: A) -> B: pass
3253 class C:
3254 def __getattr__(self, x: str, y: str) -> C: pass
3255 class D:
3256 def __getattr__(self, x: str) -> None: pass
3257 [out]
3258 main:4: error: Invalid signature "Callable[[B, A], B]" for "__getattr__"
3259 main:6: error: Invalid signature "Callable[[C, str, str], C]" for "__getattr__"
3260
3261 [case testSetattr]
3262 from typing import Union, Any
3263 class A:
3264 def __setattr__(self, name: str, value: Any) -> None: ...
3265
3266 a = A()
3267 a.test = 'hello'
3268
3269 class B:
3270 def __setattr__(self, name: str, value: Union[int, str]) -> None: ...
3271
3272 b = B()
3273 b.both = 1
3274 b.work = '2'
3275
3276 class C:
3277 def __setattr__(self, name: str, value: str) -> None: ...
3278
3279 c = C()
3280 c.fail = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "str")
3281
3282 class D:
3283 __setattr__ = 'hello' # E: Invalid signature "str" for "__setattr__"
3284
3285 d = D()
3286 d.crash = 4 # E: "D" has no attribute "crash"
3287
3288 class Ex:
3289 def __setattr__(self, name: str, value: int) -> None:...
3290 test = '42' # type: str
3291 e = Ex()
3292 e.test = 'hello'
3293 e.t = 4
3294
3295 class Super:
3296 def __setattr__(self, name: str, value: int) -> None: ...
3297
3298 class Sub(Super):
3299 ...
3300 s = Sub()
3301 s.success = 4
3302 s.fail = 'fail' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
3303
3304 [case testDecoratedSetattr]
3305 from typing import Any, Callable, TypeVar
3306
3307 T = TypeVar('T', bound=Callable)
3308
3309 def decorator(f: T) -> T:
3310 return f
3311
3312 def bad(f: Callable) -> Callable[[Any, str, int], None]:
3313 return f
3314
3315 class A:
3316 @decorator
3317 def __setattr__(self, k: str, v: str) -> None:
3318 pass
3319 class B:
3320 @bad # We test that type will be taken from decorated type, not node itself
3321 def __setattr__(self, k: str, v: str) -> None:
3322 pass
3323
3324 a: A
3325 a.foo = 'a'
3326 a.bar = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "str")
3327
3328 b: B
3329 b.good = 1
3330 b.bad = 'a' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
3331 [builtins fixtures/tuple.pyi]
3332
3333 [case testSetattrSignature]
3334 from typing import Any
3335
3336 class Test:
3337 def __setattr__() -> None: ... \
3338 # E: Invalid signature "Callable[[], None]" for "__setattr__" \
3339 # E: Method must have at least one argument. Did you forget the "self" argument?
3340
3341 t = Test()
3342 t.crash = 'test' # E: Attribute function "__setattr__" with type "Callable[[], None]" does not accept self argument \
3343 # E: "Test" has no attribute "crash"
3344
3345 class A:
3346 def __setattr__(self): ... # E: Invalid signature "Callable[[A], Any]" for "__setattr__"
3347 a = A()
3348 a.test = 4 # E: "A" has no attribute "test"
3349
3350 class B:
3351 def __setattr__(self, name, value: int): ...
3352 b = B()
3353 b.integer = 5
3354
3355 class C:
3356 def __setattr__(self, name: int, value: int) -> None: ... # E: Invalid signature "Callable[[C, int, int], None]" for "__setattr__"
3357 c = C()
3358 c.check = 13
3359
3360 class X:
3361 __setattr__ = ... # type: Any
3362
3363 [case testGetattrAndSetattr]
3364 from typing import Any
3365 class A:
3366 def __setattr__(self, name: str, value: Any) -> None: ...
3367 def __getattr__(self, name: str) -> Any: ...
3368 a = A()
3369 a.test = 4
3370 t = a.test
3371
3372 class B:
3373 def __setattr__(self, name: str, value: int) -> None: ...
3374 def __getattr__(self, name: str) -> str: ...
3375 integer = 0
3376 b = B()
3377 b.at = '3' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
3378 if int():
3379 integer = b.at # E: Incompatible types in assignment (expression has type "str", variable has type "int")
3380
3381 [case testSetattrKeywordArg]
3382 from typing import Any
3383
3384 class C:
3385 def __setattr__(self, key: str, value: Any, p: bool = False) -> None: ...
3386
3387 c: C
3388 c.__setattr__("x", 42, p=True)
3389
3390 -- CallableType objects
3391 -- ----------------
3392
3393
3394 [case testCallableObject]
3395 class A:
3396 def __call__(self, x: 'A') -> 'A':
3397 pass
3398 class B: pass
3399
3400 a = A()
3401 b = B()
3402
3403 a() # E: Missing positional argument "x" in call to "__call__" of "A"
3404 a(a, a) # E: Too many arguments for "__call__" of "A"
3405 if int():
3406 a = a(a)
3407 if int():
3408 a = a(b) # E: Argument 1 to "__call__" of "A" has incompatible type "B"; expected "A"
3409 if int():
3410 b = a(a) # E: Incompatible types in assignment (expression has type "A", variable has type "B")
3411
3412
3413 -- __new__
3414 -- --------
3415
3416
3417 [case testConstructInstanceWith__new__]
3418 from typing import Optional
3419 class C:
3420 def __new__(cls, foo: Optional[int] = None) -> 'C':
3421 obj = object.__new__(cls)
3422 return obj
3423
3424 x = C(foo=12)
3425 x.a # E: "C" has no attribute "a"
3426 C(foo='') # E: Argument "foo" to "C" has incompatible type "str"; expected "int | None"
3427 [builtins fixtures/__new__.pyi]
3428
3429 [case testConstructInstanceWithDynamicallyTyped__new__]
3430 class C:
3431 def __new__(cls, foo):
3432 obj = object.__new__(cls)
3433 return obj
3434
3435 x = C(foo=12)
3436 x = C(foo='x')
3437 x.a # E: "C" has no attribute "a"
3438 C(bar='') # E: Unexpected keyword argument "bar" for "C"
3439 [builtins fixtures/__new__.pyi]
3440
3441 [case testClassWith__new__AndCompatibilityWithType]
3442 from typing import Optional
3443 class C:
3444 def __new__(cls, foo: Optional[int] = None) -> 'C':
3445 obj = object.__new__(cls)
3446 return obj
3447 def f(x: type) -> None: pass
3448 def g(x: int) -> None: pass
3449 f(C)
3450 g(C) # E: Argument 1 to "g" has incompatible type "type[C]"; expected "int"
3451 [builtins fixtures/__new__.pyi]
3452
3453 [case testClassWith__new__AndCompatibilityWithType2]
3454 class C:
3455 def __new__(cls, foo):
3456 obj = object.__new__(cls)
3457 return obj
3458 def f(x: type) -> None: pass
3459 def g(x: int) -> None: pass
3460 f(C)
3461 g(C) # E: Argument 1 to "g" has incompatible type "type[C]"; expected "int"
3462 [builtins fixtures/__new__.pyi]
3463
3464 [case testGenericClassWith__new__]
3465 from typing import TypeVar, Generic
3466 T = TypeVar('T')
3467 class C(Generic[T]):
3468 def __new__(cls, foo: T) -> 'C[T]':
3469 obj = object.__new__(cls)
3470 return obj
3471 def set(self, x: T) -> None: pass
3472 c = C('')
3473 c.set('')
3474 c.set(1) # E: Argument 1 to "set" of "C" has incompatible type "int"; expected "str"
3475 [builtins fixtures/__new__.pyi]
3476
3477 [case testOverloaded__new__]
3478 from foo import *
3479 [file foo.pyi]
3480 from typing import overload
3481 class C:
3482 @overload
3483 def __new__(cls, foo: int) -> 'C':
3484 obj = object.__new__(cls)
3485 return obj
3486 @overload
3487 def __new__(cls, x: str, y: str) -> 'C':
3488 obj = object.__new__(cls)
3489 return obj
3490 c = C(1)
3491 c.a # E: "C" has no attribute "a"
3492 C('', '')
3493 C('') # E: No overload variant of "C" matches argument type "str" \
3494 # N: Possible overload variants: \
3495 # N: def C(foo: int) -> C \
3496 # N: def C(x: str, y: str) -> C
3497 [builtins fixtures/__new__.pyi]
3498
3499
3500 -- Special cases
3501 -- -------------
3502
3503
3504 [case testSubclassInt]
3505 import typing
3506 class A(int): pass
3507 n = 0
3508 if int():
3509 n = A()
3510 a = A()
3511 if int():
3512 a = 0 # E: Incompatible types in assignment (expression has type "int", variable has type "A")
3513
3514 [case testForwardReferenceToNestedClass]
3515 def f(o: 'B.C') -> None:
3516 o.f('') # E: Argument 1 to "f" of "C" has incompatible type "str"; expected "int"
3517
3518 class B:
3519 class C:
3520 def f(self, x: int) -> None: pass
3521 [out]
3522
3523 [case testForwardReferenceToNestedClassDeep]
3524 def f(o: 'B.C.D') -> None:
3525 o.f('') # E: Argument 1 to "f" of "D" has incompatible type "str"; expected "int"
3526
3527 class B:
3528 class C:
3529 class D:
3530 def f(self, x: int) -> None: pass
3531 [out]
3532
3533 [case testForwardReferenceToNestedClassWithinClass]
3534 class B:
3535 def f(self, o: 'C.D') -> None:
3536 o.f('') # E: Argument 1 to "f" of "D" has incompatible type "str"; expected "int"
3537
3538 class C:
3539 class D:
3540 def f(self, x: int) -> None: pass
3541 [out]
3542
3543 [case testClassVsInstanceDisambiguation]
3544 class A: pass
3545 def f(x: A) -> None: pass
3546 f(A) # E: Argument 1 to "f" has incompatible type "type[A]"; expected "A"
3547 [out]
3548
3549 -- TODO
3550 -- attribute inherited from superclass; assign in __init__
3551 -- refer to attribute before type has been inferred (the initialization in
3552 -- __init__ has not been analyzed)
3553
3554 [case testAnyBaseClassUnconstrainedConstructor]
3555 from typing import Any
3556 B = None # type: Any
3557 class C(B): pass
3558 C(0)
3559 C(arg=0)
3560 [out]
3561
3562 [case testErrorMapToSupertype]
3563 import typing
3564 class X(Nope): pass # E: Name "Nope" is not defined
3565 a, b = X() # Used to crash here (#2244)
3566
3567
3568 -- Class-valued attributes
3569 -- -----------------------
3570
3571 [case testClassValuedAttributesBasics]
3572 class A: ...
3573 class B:
3574 a = A
3575 bad = lambda: 42
3576
3577 B().bad() # E: Attribute function "bad" with type "Callable[[], int]" does not accept self argument
3578 reveal_type(B.a) # N: Revealed type is "def () -> __main__.A"
3579 reveal_type(B().a) # N: Revealed type is "def () -> __main__.A"
3580 reveal_type(B().a()) # N: Revealed type is "__main__.A"
3581
3582 class C:
3583 a = A
3584 def __init__(self) -> None:
3585 self.aa = self.a()
3586
3587 reveal_type(C().aa) # N: Revealed type is "__main__.A"
3588 [out]
3589
3590 [case testClassValuedAttributesGeneric]
3591 from typing import Generic, TypeVar, Type
3592 T = TypeVar('T')
3593
3594 class A(Generic[T]):
3595 def __init__(self, x: T) -> None:
3596 self.x = x
3597 class B(Generic[T]):
3598 a: Type[A[T]] = A
3599
3600 reveal_type(B[int]().a) # N: Revealed type is "type[__main__.A[builtins.int]]"
3601 B[int]().a('hi') # E: Argument 1 to "A" has incompatible type "str"; expected "int"
3602
3603 class C(Generic[T]):
3604 a = A
3605 def __init__(self) -> None:
3606 self.aa = self.a(42)
3607
3608 reveal_type(C().aa) # N: Revealed type is "__main__.A[builtins.int]"
3609 [out]
3610
3611 [case testClassValuedAttributesAlias]
3612 from typing import Generic, TypeVar
3613 T = TypeVar('T')
3614 S = TypeVar('S')
3615
3616 class A(Generic[T, S]): ...
3617
3618 SameA = A[T, T]
3619
3620 class B:
3621 a_any = SameA
3622 a_int = SameA[int]
3623
3624 reveal_type(B().a_any) # N: Revealed type is "def () -> __main__.A[Any, Any]"
3625 reveal_type(B().a_int()) # N: Revealed type is "__main__.A[builtins.int, builtins.int]"
3626
3627 class C:
3628 a_int = SameA[int]
3629 def __init__(self) -> None:
3630 self.aa = self.a_int()
3631
3632 reveal_type(C().aa) # N: Revealed type is "__main__.A[builtins.int, builtins.int]"
3633 [out]
3634
3635
3636 -- Type[C]
3637 -- -------
3638
3639
3640 [case testTypeUsingTypeCBasic]
3641 from typing import Type
3642 class User: pass
3643 class ProUser(User): pass
3644 def new_user(user_class: Type[User]) -> User:
3645 return user_class()
3646 reveal_type(new_user(User)) # N: Revealed type is "__main__.User"
3647 reveal_type(new_user(ProUser)) # N: Revealed type is "__main__.User"
3648 [out]
3649
3650 [case testTypeUsingTypeCDefaultInit]
3651 from typing import Type
3652 class B:
3653 pass
3654 def f(A: Type[B]) -> None:
3655 A(0) # E: Too many arguments for "B"
3656 A()
3657 [out]
3658
3659 [case testTypeUsingTypeCInitWithArg]
3660 from typing import Type
3661 class B:
3662 def __init__(self, a: int) -> None: pass
3663 def f(A: Type[B]) -> None:
3664 A(0)
3665 A() # E: Missing positional argument "a" in call to "B"
3666 [out]
3667
3668 [case testTypeUsingTypeCTypeVar]
3669 from typing import Type, TypeVar
3670 class User: pass
3671 class ProUser(User): pass
3672 U = TypeVar('U', bound=User)
3673 def new_user(user_class: Type[U]) -> U:
3674 user = user_class()
3675 reveal_type(user)
3676 return user
3677 pro_user = new_user(ProUser)
3678 reveal_type(pro_user)
3679 [out]
3680 main:7: note: Revealed type is "U`-1"
3681 main:10: note: Revealed type is "__main__.ProUser"
3682
3683 [case testTypeUsingTypeCTypeVarDefaultInit]
3684 from typing import Type, TypeVar
3685 class B:
3686 pass
3687 T = TypeVar('T', bound=B)
3688 def f(A: Type[T]) -> None:
3689 A()
3690 A(0) # E: Too many arguments for "B"
3691 [out]
3692
3693 [case testTypeUsingTypeCTypeVarWithInit]
3694 from typing import Type, TypeVar
3695 class B:
3696 def __init__(self, a: int) -> None: pass
3697 T = TypeVar('T', bound=B)
3698 def f(A: Type[T]) -> None:
3699 A() # E: Missing positional argument "a" in call to "B"
3700 A(0)
3701 [out]
3702
3703 [case testTypeUsingTypeCTwoTypeVars]
3704 from typing import Type, TypeVar
3705 class User: pass
3706 class ProUser(User): pass
3707 class WizUser(ProUser): pass
3708 U = TypeVar('U', bound=User)
3709 def new_user(u_c: Type[U]) -> U: pass
3710 P = TypeVar('P', bound=ProUser)
3711 def new_pro(pro_c: Type[P]) -> P:
3712 return new_user(pro_c)
3713 wiz = new_pro(WizUser)
3714 reveal_type(wiz)
3715 def error(u_c: Type[U]) -> P: # Error here, see below
3716 return new_pro(u_c) # Error here, see below
3717 [out]
3718 main:11: note: Revealed type is "__main__.WizUser"
3719 main:12: error: A function returning TypeVar should receive at least one argument containing the same TypeVar
3720 main:12: note: Consider using the upper bound "ProUser" instead
3721 main:13: error: Value of type variable "P" of "new_pro" cannot be "U"
3722 main:13: error: Incompatible return value type (got "U", expected "P")
3723
3724 [case testTypeUsingTypeCCovariance]
3725 from typing import Type, TypeVar
3726 class User: pass
3727 class ProUser(User): pass
3728 def new_user(user_class: Type[User]) -> User:
3729 return user_class()
3730 def new_pro_user(user_class: Type[ProUser]):
3731 new_user(user_class)
3732 [out]
3733
3734 [case testAllowCovariantArgsInConstructor]
3735 from typing import Generic, TypeVar
3736
3737 T_co = TypeVar('T_co', covariant=True)
3738
3739 class C(Generic[T_co]):
3740 def __init__(self, x: T_co) -> None: # This should be allowed
3741 self.x = x
3742 def meth(self) -> None:
3743 reveal_type(self.x) # N: Revealed type is "T_co`1"
3744
3745 reveal_type(C(1).x) # N: Revealed type is "builtins.int"
3746 [builtins fixtures/property.pyi]
3747 [out]
3748
3749 [case testTypeUsingTypeCErrorCovariance]
3750 from typing import Type, TypeVar
3751 class User: pass
3752 def new_user(user_class: Type[User]):
3753 return user_class()
3754 def foo(arg: Type[int]):
3755 new_user(arg) # E: Argument 1 to "new_user" has incompatible type "type[int]"; expected "type[User]"
3756 [out]
3757
3758 [case testTypeUsingTypeCUnionOverload]
3759 from foo import *
3760 [file foo.pyi]
3761 from typing import Type, Union, overload
3762 class X:
3763 @overload
3764 def __init__(self) -> None: pass
3765 @overload
3766 def __init__(self, a: int) -> None: pass
3767 class Y:
3768 def __init__(self) -> None: pass
3769 def bar(o: Type[Union[X, Y]]): pass
3770 bar(X)
3771 bar(Y)
3772 [out]
3773
3774 [case testTypeUsingTypeCTypeAny]
3775 from typing import Type, Any
3776 def foo(arg: Type[Any]):
3777 x = arg()
3778 x = arg(0)
3779 x = arg('', ())
3780 reveal_type(x) # N: Revealed type is "Any"
3781 x.foo
3782 class X: pass
3783 foo(X)
3784 [builtins fixtures/tuple.pyi]
3785 [out]
3786
3787 [case testTypeUsingTypeCTypeAnyMember]
3788 from typing import Type, Any
3789 def foo(arg: Type[Any]):
3790 x = arg.member_name
3791 arg.new_member_name = 42
3792 # Member access is ok and types as Any
3793 reveal_type(x) # N: Revealed type is "Any"
3794 # But type[Any] is distinct from Any
3795 y: int = arg # E: Incompatible types in assignment (expression has type "type[Any]", variable has type "int")
3796 [out]
3797
3798 [case testTypeUsingTypeCTypeAnyMemberFallback]
3799 from typing import Type, Any
3800 def foo(arg: Type[Any]):
3801 reveal_type(arg.__str__) # N: Revealed type is "def () -> builtins.str"
3802 reveal_type(arg.mro()) # N: Revealed type is "builtins.list[builtins.type]"
3803 [builtins fixtures/type.pyi]
3804 [out]
3805
3806 [case testTypeUsingTypeCTypeNoArg]
3807 from typing import Type
3808 def foo(arg: Type):
3809 x = arg()
3810 reveal_type(x) # N: Revealed type is "Any"
3811 class X: pass
3812 foo(X)
3813 [out]
3814
3815 [case testTypeUsingTypeCBuiltinType]
3816 from typing import Type
3817 def foo(arg: type): pass
3818 class X: pass
3819 def bar(arg: Type[X]):
3820 foo(arg)
3821 foo(X)
3822 [builtins fixtures/tuple.pyi]
3823 [out]
3824
3825 [case testTypeUsingTypeCClassMethod]
3826 from typing import Type
3827 class User:
3828 @classmethod
3829 def foo(cls) -> int: pass
3830 def bar(self) -> int: pass
3831 def process(cls: Type[User]):
3832 reveal_type(cls.foo()) # N: Revealed type is "builtins.int"
3833 obj = cls()
3834 reveal_type(cls.bar(obj)) # N: Revealed type is "builtins.int"
3835 cls.mro() # Defined in class type
3836 cls.error # E: "type[User]" has no attribute "error"
3837 [builtins fixtures/classmethod.pyi]
3838 [out]
3839
3840 [case testTypeUsingTypeCClassMethodUnion]
3841 from typing import Type, Union
3842 class User:
3843 @classmethod
3844 def foo(cls) -> int: pass
3845 def bar(self) -> int: pass
3846 class ProUser(User): pass
3847 class BasicUser(User): pass
3848 def process(cls: Type[Union[BasicUser, ProUser]]):
3849 cls.foo()
3850 obj = cls()
3851 cls.bar(obj)
3852 cls.mro() # Defined in class type
3853 cls.error # E: Item "type" of "type[BasicUser] | type[ProUser]" has no attribute "error"
3854 [builtins fixtures/classmethod.pyi]
3855 [out]
3856
3857 [case testTypeUsingTypeCClassMethodFromTypeVar]
3858 from typing import Type, TypeVar
3859 class User:
3860 @classmethod
3861 def foo(cls) -> int: pass
3862 def bar(self) -> int: pass
3863 U = TypeVar('U', bound=User)
3864 def process(cls: Type[U]):
3865 reveal_type(cls.foo()) # N: Revealed type is "builtins.int"
3866 obj = cls()
3867 reveal_type(cls.bar(obj)) # N: Revealed type is "builtins.int"
3868 cls.mro() # Defined in class type
3869 cls.error # E: "type[U]" has no attribute "error"
3870 [builtins fixtures/classmethod.pyi]
3871 [out]
3872
3873 [case testTypeUsingTypeCClassMethodFromTypeVarUnionBound]
3874 # Ideally this would work, but not worth the effort; just don't crash
3875 from typing import Type, TypeVar, Union
3876 class User:
3877 @classmethod
3878 def foo(cls) -> int: pass
3879 def bar(self) -> int: pass
3880 class ProUser(User): pass
3881 class BasicUser(User): pass
3882 U = TypeVar('U', bound=Union[ProUser, BasicUser])
3883 def process(cls: Type[U]):
3884 cls.foo()
3885 obj = cls()
3886 cls.bar(obj)
3887 cls.mro() # Defined in class type
3888 cls.error # E: "type[U]" has no attribute "error"
3889 [builtins fixtures/classmethod.pyi]
3890 [out]
3891
3892 [case testTypeUsingTypeCConstructorReturnFromTypeVarUnionBound]
3893 from typing import Optional, Type, TypeVar, Union
3894
3895 class A:
3896 def __init__(self, value: str = "") -> None: pass
3897 class B:
3898 def __init__(self, value: str = "") -> None: pass
3899
3900 T = TypeVar("T", bound=Union[A, B])
3901
3902 def make(ftype: Type[T], value: Optional[str]) -> T:
3903 if value is None:
3904 return ftype()
3905 return ftype(value)
3906
3907 reveal_type(make(A, "a")) # N: Revealed type is "__main__.A"
3908 reveal_type(make(B, None)) # N: Revealed type is "__main__.B"
3909
3910 [case testTypeUsingTypeCErrorUnsupportedType]
3911 from typing import Type, Tuple
3912 def foo(arg: Type[Tuple[int]]):
3913 arg() # E: Cannot instantiate type "type[tuple[int]]"
3914 [builtins fixtures/tuple.pyi]
3915
3916 [case testTypeUsingTypeCOverloadedClass]
3917 from foo import *
3918 [file foo.pyi]
3919 from typing import Type, TypeVar, overload
3920 class User:
3921 @overload
3922 def __init__(self) -> None: pass
3923 @overload
3924 def __init__(self, arg: int) -> None: pass
3925 @classmethod
3926 def foo(cls) -> None: pass
3927 U = TypeVar('U', bound=User)
3928 def new(uc: Type[U]) -> U:
3929 uc.foo()
3930 u = uc()
3931 u.foo()
3932 if 1:
3933 u = uc(0)
3934 u.foo()
3935 uc('') # Error
3936 u.foo(0) # Error
3937 return uc()
3938 u = new(User)
3939 [builtins fixtures/classmethod.pyi]
3940 [out]
3941 tmp/foo.pyi:17: error: No overload variant of "User" matches argument type "str"
3942 tmp/foo.pyi:17: note: Possible overload variants:
3943 tmp/foo.pyi:17: note: def User() -> U
3944 tmp/foo.pyi:17: note: def User(arg: int) -> U
3945 tmp/foo.pyi:18: error: Too many arguments for "foo" of "User"
3946
3947 [case testTypeUsingTypeCInUpperBound]
3948 from typing import TypeVar, Type
3949 class B: pass
3950 T = TypeVar('T', bound=Type[B])
3951 def f(a: T): pass
3952 [out]
3953
3954 [case testTypeUsingTypeCTuple]
3955 from typing import Type, Tuple
3956 def f(a: Type[Tuple[int, int]]):
3957 a() # E: Cannot instantiate type "type[tuple[int, int]]"
3958 [builtins fixtures/tuple.pyi]
3959
3960 [case testTypeUsingTypeCNamedTuple]
3961 from typing import Type, NamedTuple
3962 N = NamedTuple('N', [('x', int), ('y', int)])
3963 def f(a: Type[N]):
3964 a()
3965 [builtins fixtures/list.pyi]
3966 [out]
3967 main:4: error: Missing positional arguments "x", "y" in call to "N"
3968
3969 [case testTypeUsingTypeCJoin]
3970 from typing import Type
3971 class B: pass
3972 class C(B): pass
3973 class D(B): pass
3974 def foo(c: Type[C], d: Type[D]) -> None:
3975 x = [c, d]
3976 reveal_type(x)
3977
3978 [builtins fixtures/list.pyi]
3979 [out]
3980 main:7: note: Revealed type is "builtins.list[type[__main__.B]]"
3981
3982 [case testTypeEquivalentTypeAny]
3983 from typing import Type, Any
3984
3985 a: Type[Any]
3986 b = a # type: type
3987
3988 x: type
3989 y = x # type: Type[Any]
3990
3991 class C: ...
3992
3993 p: type
3994 q = p # type: Type[C]
3995
3996 [builtins fixtures/list.pyi]
3997 [out]
3998
3999 [case testTypeEquivalentTypeAny2]
4000 from typing import Type, Any, TypeVar, Generic
4001
4002 class C: ...
4003 x: type
4004 y: Type[Any]
4005 z: Type[C]
4006
4007 lst = [x, y, z]
4008 reveal_type(lst) # N: Revealed type is "builtins.list[builtins.type]"
4009
4010 T1 = TypeVar('T1', bound=type)
4011 T2 = TypeVar('T2', bound=Type[Any])
4012 class C1(Generic[T1]): ...
4013 class C2(Generic[T2]): ...
4014
4015 C1[Type[Any]], C2[type] # both these should not fail
4016 [builtins fixtures/list.pyi]
4017 [out]
4018
4019 [case testTypeEquivalentTypeAnyEdgeCase]
4020 class C:
4021 pass
4022
4023 class M(type):
4024 def __init__(cls, x) -> None:
4025 type.__init__(cls, x)
4026
4027 class Mbad(type):
4028 def __init__(cls, x) -> None:
4029 type.__init__(C(), x) # E: Argument 1 to "__init__" of "type" has incompatible type "C"; expected "type"
4030 [builtins fixtures/primitives.pyi]
4031 [out]
4032
4033 [case testTypeMatchesOverloadedFunctions]
4034 from foo import *
4035 [file foo.pyi]
4036 from typing import Type, overload, Any
4037
4038 class User: pass
4039 UserType = User # type: Type[User]
4040
4041 @overload
4042 def f(a: int) -> Any: pass
4043 @overload
4044 def f(a: object) -> int: pass
4045
4046 reveal_type(f(User)) # N: Revealed type is "builtins.int"
4047 reveal_type(f(UserType)) # N: Revealed type is "builtins.int"
4048 [builtins fixtures/classmethod.pyi]
4049 [out]
4050
4051 [case testTypeMatchesGeneralTypeInOverloadedFunctions]
4052 from foo import *
4053 [file foo.pyi]
4054 from typing import Type, overload
4055
4056 class User: pass
4057 UserType = User # type: Type[User]
4058
4059 @overload
4060 def f(a: type) -> int:
4061 return 1
4062 @overload
4063 def f(a: int) -> str:
4064 return "a"
4065
4066 reveal_type(f(User)) # N: Revealed type is "builtins.int"
4067 reveal_type(f(UserType)) # N: Revealed type is "builtins.int"
4068 reveal_type(f(1)) # N: Revealed type is "builtins.str"
4069 [builtins fixtures/classmethod.pyi]
4070 [out]
4071
4072 [case testTypeMatchesSpecificTypeInOverloadedFunctions]
4073 from foo import *
4074 [file foo.pyi]
4075 from typing import Type, overload
4076
4077 class User: pass
4078 UserType = User # type: Type[User]
4079
4080 @overload
4081 def f(a: User) -> User:
4082 return User()
4083 @overload
4084 def f(a: Type[User]) -> int:
4085 return 1
4086 @overload
4087 def f(a: int) -> str:
4088 return "a"
4089
4090 reveal_type(f(User)) # N: Revealed type is "builtins.int"
4091 reveal_type(f(UserType)) # N: Revealed type is "builtins.int"
4092 reveal_type(f(User())) # N: Revealed type is "foo.User"
4093 reveal_type(f(1)) # N: Revealed type is "builtins.str"
4094 [builtins fixtures/classmethod.pyi]
4095 [out]
4096
4097 [case testMixingTypeTypeInOverloadedFunctions]
4098 from foo import *
4099 [file foo.pyi]
4100 from typing import Type, overload
4101
4102 class User: pass
4103
4104 @overload
4105 def f(a: User) -> Type[User]:
4106 return User
4107 @overload
4108 def f(a: Type[User]) -> User:
4109 return a()
4110 @overload
4111 def f(a: int) -> Type[User]:
4112 return User
4113 @overload
4114 def f(a: str) -> User:
4115 return User()
4116
4117 reveal_type(f(User())) # N: Revealed type is "type[foo.User]"
4118 reveal_type(f(User)) # N: Revealed type is "foo.User"
4119 reveal_type(f(3)) # N: Revealed type is "type[foo.User]"
4120 reveal_type(f("hi")) # N: Revealed type is "foo.User"
4121 [builtins fixtures/classmethod.pyi]
4122 [out]
4123
4124 [case testGeneralTypeMatchesSpecificTypeInOverloadedFunctions]
4125 from foo import *
4126 [file foo.pyi]
4127 from typing import Type, Any, overload
4128
4129 class User: pass
4130
4131 @overload
4132 def f(a: Type[User]) -> None: pass
4133 @overload
4134 def f(a: int) -> None: pass
4135
4136 def mock_1() -> type: return User
4137 def mock_2() -> Type[Any]: return User
4138
4139 f(User)
4140 f(mock_1())
4141 f(mock_2())
4142 [builtins fixtures/classmethod.pyi]
4143 [out]
4144
4145 [case testNonTypeDoesNotMatchOverloadedFunctions]
4146 from foo import *
4147 [file foo.pyi]
4148 from typing import Type, overload
4149
4150 class User: pass
4151
4152 @overload
4153 def f(a: Type[User]) -> None: pass
4154 @overload
4155 def f(a: type) -> None: pass
4156
4157 f(3) # E: No overload variant of "f" matches argument type "int" \
4158 # N: Possible overload variants: \
4159 # N: def f(a: type[User]) -> None \
4160 # N: def f(a: type) -> None
4161 [builtins fixtures/classmethod.pyi]
4162 [out]
4163
4164 [case testInstancesDoNotMatchTypeInOverloadedFunctions]
4165 from foo import *
4166 [file foo.pyi]
4167 from typing import Type, overload
4168
4169 class User: pass
4170
4171 @overload
4172 def f(a: Type[User]) -> None: pass
4173 @overload
4174 def f(a: int) -> None: pass
4175
4176 f(User)
4177 f(User()) # E: No overload variant of "f" matches argument type "User" \
4178 # N: Possible overload variants: \
4179 # N: def f(a: type[User]) -> None \
4180 # N: def f(a: int) -> None
4181 [builtins fixtures/classmethod.pyi]
4182 [out]
4183
4184 [case testTypeCovarianceWithOverloadedFunctions]
4185 from foo import *
4186 [file foo.pyi]
4187 from typing import Type, overload
4188
4189 class A: pass
4190 class B(A): pass
4191 class C(B): pass
4192 AType = A # type: Type[A]
4193 BType = B # type: Type[B]
4194 CType = C # type: Type[C]
4195
4196 @overload
4197 def f(a: Type[B]) -> None: pass
4198 @overload
4199 def f(a: int) -> None: pass
4200
4201 f(A) # E: Argument 1 to "f" has incompatible type "type[A]"; expected "type[B]"
4202 f(B)
4203 f(C)
4204 f(AType) # E: Argument 1 to "f" has incompatible type "type[A]"; expected "type[B]"
4205 f(BType)
4206 f(CType)
4207 [builtins fixtures/classmethod.pyi]
4208 [out]
4209
4210
4211 [case testOverloadedCovariantTypesFail]
4212 from foo import *
4213 [file foo.pyi]
4214 from typing import Type, overload
4215
4216 class A: pass
4217 class B(A): pass
4218
4219 @overload
4220 def f(a: Type[B]) -> int: pass # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
4221 @overload
4222 def f(a: Type[A]) -> str: pass
4223 [builtins fixtures/classmethod.pyi]
4224 [out]
4225
4226 [case testDistinctOverloadedCovariantTypesSucceed]
4227 from foo import *
4228 [file foo.pyi]
4229 from typing import Type, overload
4230
4231 class A: pass
4232 class AChild(A): pass
4233 class B: pass
4234 class BChild(B): pass
4235
4236 @overload
4237 def f(a: Type[A]) -> int: pass
4238 @overload
4239 def f(a: Type[B]) -> str: pass
4240 @overload
4241 def f(a: A) -> A: pass
4242 @overload
4243 def f(a: B) -> B: pass
4244
4245 reveal_type(f(A)) # N: Revealed type is "builtins.int"
4246 reveal_type(f(AChild)) # N: Revealed type is "builtins.int"
4247 reveal_type(f(B)) # N: Revealed type is "builtins.str"
4248 reveal_type(f(BChild)) # N: Revealed type is "builtins.str"
4249
4250 reveal_type(f(A())) # N: Revealed type is "foo.A"
4251 reveal_type(f(AChild())) # N: Revealed type is "foo.A"
4252 reveal_type(f(B())) # N: Revealed type is "foo.B"
4253 reveal_type(f(BChild())) # N: Revealed type is "foo.B"
4254 [builtins fixtures/classmethod.pyi]
4255 [out]
4256
4257 [case testSubtypeWithMoreOverloadsThanSupertypeSucceeds]
4258 from foo import *
4259 [file foo.pyi]
4260 from typing import overload
4261
4262
4263 class X: pass
4264 class Y: pass
4265 class Z: pass
4266
4267
4268 class A:
4269 @overload
4270 def f(self, x: X) -> X: pass
4271 @overload
4272 def f(self, y: Y) -> Y: pass
4273
4274 class B(A):
4275 @overload
4276 def f(self, x: X) -> X: pass
4277 @overload
4278 def f(self, y: Y) -> Y: pass
4279 @overload
4280 def f(self, z: Z) -> Z: pass
4281 [builtins fixtures/classmethod.pyi]
4282 [out]
4283
4284 [case testSubtypeOverloadCoveringMultipleSupertypeOverloadsSucceeds]
4285 from foo import *
4286 [file foo.pyi]
4287 from typing import overload
4288
4289
4290 class A: pass
4291 class B(A): pass
4292 class C(A): pass
4293 class D: pass
4294
4295
4296 class Super:
4297 @overload
4298 def foo(self, a: B) -> C: pass
4299 @overload
4300 def foo(self, a: C) -> A: pass
4301 @overload
4302 def foo(self, a: D) -> D: pass
4303
4304 class Sub(Super):
4305 @overload
4306 def foo(self, a: A) -> C: pass
4307 @overload
4308 def foo(self, a: D) -> D: pass
4309 [builtins fixtures/classmethod.pyi]
4310 [out]
4311
4312 [case testSubtypeOverloadWithOverlappingArgumentsButWrongReturnType]
4313 from foo import *
4314 [file foo.pyi]
4315 from typing import overload
4316
4317
4318 class A: pass
4319 class B(A): pass
4320 class C: pass
4321
4322
4323 class Super:
4324 @overload
4325 def foo(self, a: A) -> A: pass
4326 @overload
4327 def foo(self, a: C) -> C: pass
4328
4329 class Sub(Super):
4330 @overload
4331 def foo(self, a: A) -> A: pass
4332 @overload
4333 def foo(self, a: B) -> C: pass # Fail
4334 @overload
4335 def foo(self, a: C) -> C: pass
4336
4337 class Sub2(Super):
4338 @overload
4339 def foo(self, a: B) -> C: pass # Fail
4340 @overload
4341 def foo(self, a: A) -> A: pass
4342 @overload
4343 def foo(self, a: C) -> C: pass
4344
4345 class Sub3(Super):
4346 @overload
4347 def foo(self, a: A) -> int: pass
4348 @overload
4349 def foo(self, a: A) -> A: pass
4350 @overload
4351 def foo(self, a: C) -> C: pass
4352 [builtins fixtures/classmethod.pyi]
4353 [out]
4354 tmp/foo.pyi:19: error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
4355 tmp/foo.pyi:24: error: Signature of "foo" incompatible with supertype "Super"
4356 tmp/foo.pyi:24: note: Superclass:
4357 tmp/foo.pyi:24: note: @overload
4358 tmp/foo.pyi:24: note: def foo(self, a: A) -> A
4359 tmp/foo.pyi:24: note: @overload
4360 tmp/foo.pyi:24: note: def foo(self, a: C) -> C
4361 tmp/foo.pyi:24: note: Subclass:
4362 tmp/foo.pyi:24: note: @overload
4363 tmp/foo.pyi:24: note: def foo(self, a: B) -> C
4364 tmp/foo.pyi:24: note: @overload
4365 tmp/foo.pyi:24: note: def foo(self, a: A) -> A
4366 tmp/foo.pyi:24: note: @overload
4367 tmp/foo.pyi:24: note: def foo(self, a: C) -> C
4368 tmp/foo.pyi:25: error: Overloaded function signatures 1 and 2 overlap with incompatible return types
4369 tmp/foo.pyi:32: error: Signature of "foo" incompatible with supertype "Super"
4370 tmp/foo.pyi:32: note: Superclass:
4371 tmp/foo.pyi:32: note: @overload
4372 tmp/foo.pyi:32: note: def foo(self, a: A) -> A
4373 tmp/foo.pyi:32: note: @overload
4374 tmp/foo.pyi:32: note: def foo(self, a: C) -> C
4375 tmp/foo.pyi:32: note: Subclass:
4376 tmp/foo.pyi:32: note: @overload
4377 tmp/foo.pyi:32: note: def foo(self, a: A) -> int
4378 tmp/foo.pyi:32: note: @overload
4379 tmp/foo.pyi:32: note: def foo(self, a: A) -> A
4380 tmp/foo.pyi:32: note: @overload
4381 tmp/foo.pyi:32: note: def foo(self, a: C) -> C
4382 tmp/foo.pyi:35: error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
4383
4384 [case testTypeTypeOverlapsWithObjectAndType]
4385 from foo import *
4386 [file foo.pyi]
4387 from typing import Type, overload
4388
4389 class User: pass
4390
4391 @overload
4392 def f(a: Type[User]) -> int: pass # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
4393 @overload
4394 def f(a: object) -> str: pass
4395
4396 # Note: plain type is equivalent to Type[Any] so no error here
4397 @overload
4398 def g(a: Type[User]) -> int: pass
4399 @overload
4400 def g(a: type) -> str: pass
4401
4402 @overload
4403 def h(a: Type[User]) -> int: pass # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
4404 @overload
4405 def h(a: Type[object]) -> str: pass
4406 [builtins fixtures/classmethod.pyi]
4407 [out]
4408
4409 [case testTypeOverlapsWithObject]
4410 from foo import *
4411 [file foo.pyi]
4412 from typing import Type, overload
4413
4414 class User: pass
4415
4416 @overload
4417 def f(a: type) -> int: pass # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
4418 @overload
4419 def f(a: object) -> str: pass
4420 [builtins fixtures/classmethod.pyi]
4421 [out]
4422
4423 [case testTypeConstructorReturnsTypeType]
4424 class User:
4425 @classmethod
4426 def test_class_method(cls) -> int: pass
4427 @staticmethod
4428 def test_static_method() -> str: pass
4429 def test_instance_method(self) -> None: pass
4430
4431 u = User()
4432
4433 reveal_type(type(u)) # N: Revealed type is "type[__main__.User]"
4434 reveal_type(type(u).test_class_method()) # N: Revealed type is "builtins.int"
4435 reveal_type(type(u).test_static_method()) # N: Revealed type is "builtins.str"
4436 type(u).test_instance_method() # E: Missing positional argument "self" in call to "test_instance_method" of "User"
4437 [builtins fixtures/classmethod.pyi]
4438 [out]
4439
4440 [case testObfuscatedTypeConstructorReturnsTypeType]
4441 from typing import TypeVar
4442 class User: pass
4443
4444 f1 = type
4445
4446 A = TypeVar('A')
4447 def f2(func: A) -> A:
4448 return func
4449
4450 u = User()
4451
4452 reveal_type(f1(u)) # N: Revealed type is "type[__main__.User]"
4453 reveal_type(f2(type)(u)) # N: Revealed type is "type[__main__.User]"
4454 [builtins fixtures/classmethod.pyi]
4455 [out]
4456
4457 [case testTypeConstructorLookalikeFails]
4458 class User: pass
4459
4460 def fake1(a: object) -> type:
4461 return User
4462 def fake2(a: int) -> type:
4463 return User
4464
4465 reveal_type(type(User())) # N: Revealed type is "type[__main__.User]"
4466 reveal_type(fake1(User())) # N: Revealed type is "builtins.type"
4467 reveal_type(fake2(3)) # N: Revealed type is "builtins.type"
4468 [builtins fixtures/classmethod.pyi]
4469 [out]
4470
4471 [case testOtherTypeConstructorsSucceed]
4472 def foo(self) -> int: return self.attr
4473
4474 User = type('User', (object,), {'foo': foo, 'attr': 3})
4475 reveal_type(User) # N: Revealed type is "builtins.type"
4476 [builtins fixtures/args.pyi]
4477 [out]
4478
4479 [case testTypeTypeComparisonWorks]
4480 class User: pass
4481
4482 User == User
4483 User == type(User())
4484 type(User()) == User
4485 type(User()) == type(User())
4486
4487 User != User
4488 User != type(User())
4489 type(User()) != User
4490 type(User()) != type(User())
4491
4492 int == int
4493 int == type(3)
4494 type(3) == int
4495 type(3) == type(3)
4496
4497 int != int
4498 int != type(3)
4499 type(3) != int
4500 type(3) != type(3)
4501
4502 User is User
4503 User is type(User)
4504 type(User) is User
4505 type(User) is type(User)
4506
4507 int is int
4508 int is type(3)
4509 type(3) is int
4510 type(3) is type(3)
4511
4512 int.__eq__(int)
4513 int.__eq__(3, 4)
4514 [builtins fixtures/args.pyi]
4515 [out]
4516 main:33: error: Too few arguments for "__eq__" of "int"
4517 main:33: error: Unsupported operand types for == ("type[int]" and "type[int]")
4518
4519 [case testDupBaseClasses]
4520 class A:
4521 def method(self) -> str: ...
4522
4523 class B(A, A): # E: Duplicate base class "A"
4524 attr: int
4525
4526 b: B
4527
4528 reveal_type(b.method()) # N: Revealed type is "Any"
4529 reveal_type(b.missing()) # N: Revealed type is "Any"
4530 reveal_type(b.attr) # N: Revealed type is "builtins.int"
4531
4532 [case testDupBaseClassesGeneric]
4533 from typing import Generic, TypeVar
4534
4535 T = TypeVar('T')
4536 class A(Generic[T]):
4537 def method(self) -> T: ...
4538
4539 class B(A[int], A[str]): # E: Duplicate base class "A"
4540 attr: int
4541
4542 reveal_type(B().method()) # N: Revealed type is "Any"
4543 reveal_type(B().attr) # N: Revealed type is "builtins.int"
4544
4545 [case testCannotDetermineMro]
4546 class A: pass
4547 class B(A): pass
4548 class C(B): pass
4549 class D(A, B): pass # E: Cannot determine consistent method resolution order (MRO) for "D"
4550 class E(C, D): pass
4551
4552 [case testInconsistentMroLocalRef]
4553 class A: pass
4554 class B(object, A): # E: Cannot determine consistent method resolution order (MRO) for "B"
4555 def readlines(self): pass
4556 __iter__ = readlines
4557
4558 [case testDynamicMetaclass]
4559 class C(metaclass=int()): # E: Dynamic metaclass not supported for "C"
4560 pass
4561
4562 [case testDynamicMetaclassCrash]
4563 class C(metaclass=int().x): # E: Dynamic metaclass not supported for "C"
4564 pass
4565
4566 [case testVariableSubclass]
4567 class A:
4568 a = 1 # type: int
4569 class B(A):
4570 a = 1
4571 [out]
4572
4573 [case testVariableSubclassAssignMismatch]
4574 class A:
4575 a = 1 # type: int
4576 class B(A):
4577 a = "a"
4578 [out]
4579 main:4: error: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "int")
4580
4581 [case testVariableSubclassAssignment]
4582 class A:
4583 a: int
4584 class B(A):
4585 def __init__(self) -> None:
4586 self.a = "a"
4587 [out]
4588 main:5: error: Incompatible types in assignment (expression has type "str", variable has type "int")
4589
4590 [case testVariableSubclassTypeOverwrite]
4591 class A:
4592 a: int
4593 class B(A):
4594 a: str
4595 class C(B):
4596 a = "a"
4597 [out]
4598 main:4: error: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "int")
4599
4600 [case testVariableSubclassTypeOverwriteImplicit]
4601 class A:
4602 a = 1
4603 class B(A):
4604 a: str
4605 [out]
4606 main:4: error: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "int")
4607
4608 [case testVariableSuperUsage]
4609 class A:
4610 a = [] # type: list
4611 class B(A):
4612 a = [1, 2]
4613 class C(B):
4614 a = B.a + [3]
4615 [builtins fixtures/list.pyi]
4616 [out]
4617
4618 [case testClassAllBases]
4619 from typing import Union
4620 class A:
4621 a: Union[int, str]
4622 class B(A):
4623 a = 1
4624 class C(B):
4625 a = "str"
4626 class D(A):
4627 a = "str"
4628 [out]
4629 main:7: error: Incompatible types in assignment (expression has type "str", base class "B" defined the type as "int")
4630
4631 [case testVariableTypeVar]
4632 from typing import TypeVar, Generic
4633 T = TypeVar('T')
4634 class A(Generic[T]):
4635 a: T
4636 class B(A[int]):
4637 a = 1
4638
4639 [case testVariableTypeVarInvalid]
4640 from typing import TypeVar, Generic
4641 T = TypeVar('T')
4642 class A(Generic[T]):
4643 a: T
4644 class B(A[int]):
4645 a = "abc"
4646 [out]
4647 main:6: error: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "int")
4648
4649 [case testVariableTypeVarIndirectly]
4650 from typing import TypeVar, Generic
4651 T = TypeVar('T')
4652 class A(Generic[T]):
4653 a: T
4654 class B(A[int]):
4655 pass
4656 class C(B):
4657 a = "a"
4658 [out]
4659 main:8: error: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "int")
4660
4661 [case testVariableTypeVarList]
4662 from typing import List, TypeVar, Generic
4663 T = TypeVar('T')
4664 class A(Generic[T]):
4665 a: List[T]
4666 b: List[T]
4667 class B(A[int]):
4668 a = [1]
4669 b = ['']
4670 [builtins fixtures/list.pyi]
4671 [out]
4672 main:8: error: List item 0 has incompatible type "str"; expected "int"
4673
4674 [case testVariableMethod]
4675 class A:
4676 def a(self) -> None: pass
4677 b = 1
4678 class B(A):
4679 a = 1 # E: Incompatible types in assignment (expression has type "int", base class "A" defined the type as "Callable[[], None]")
4680 def b(self) -> None: pass # E: Signature of "b" incompatible with supertype "A" \
4681 # N: Superclass: \
4682 # N: int \
4683 # N: Subclass: \
4684 # N: def b(self) -> None
4685
4686 [case testVariableProperty]
4687 class A:
4688 @property
4689 def a(self) -> bool: pass
4690 class B(A):
4691 a: bool
4692 class C(A):
4693 a = True
4694 class D(A):
4695 a = 1
4696 [builtins fixtures/property.pyi]
4697 [out]
4698 main:9: error: Incompatible types in assignment (expression has type "int", base class "A" defined the type as "bool")
4699
4700 [case testVariableOverwriteAny]
4701 from typing import Any
4702 class A:
4703 a = 1
4704 class B(A):
4705 a = 'x' # type: Any
4706 [out]
4707
4708 [case testInstanceMethodOverwrite]
4709 class B():
4710 def n(self, a: int) -> None: pass
4711 class C(B):
4712 def m(self, a: int) -> None: pass
4713 n = m
4714 [out]
4715
4716 [case testInstanceMethodOverwriteError]
4717 class B():
4718 def n(self, a: int) -> None: pass
4719 class C(B):
4720 def m(self, a: str) -> None: pass
4721 n = m
4722 [out]
4723 main:5: error: Incompatible types in assignment (expression has type "Callable[[str], None]", base class "B" defined the type as "Callable[[int], None]")
4724
4725 [case testInstanceMethodOverwriteTypevar]
4726 from typing import Generic, TypeVar
4727 T = TypeVar("T")
4728 class B(Generic[T]):
4729 def n(self, a: T) -> None: pass
4730 class C(B[int]):
4731 def m(self, a: int) -> None: pass
4732 n = m
4733
4734 [case testInstanceMethodOverwriteTwice]
4735 class I:
4736 def foo(self) -> None: pass
4737 class A(I):
4738 def foo(self) -> None: pass
4739 class B(A):
4740 def bar(self) -> None: pass
4741 foo = bar
4742 class C(B):
4743 def bar(self) -> None: pass
4744 foo = bar
4745
4746 [case testClassMethodOverwrite]
4747 class B():
4748 @classmethod
4749 def n(self, a: int) -> None: pass
4750 class C(B):
4751 @classmethod
4752 def m(self, a: int) -> None: pass
4753 n = m
4754 [builtins fixtures/classmethod.pyi]
4755 [out]
4756
4757 [case testClassMethodOverwriteError]
4758 class B():
4759 @classmethod
4760 def n(self, a: int) -> None: pass
4761 class C(B):
4762 @classmethod
4763 def m(self, a: str) -> None: pass
4764 n = m
4765 [builtins fixtures/classmethod.pyi]
4766 [out]
4767 main:7: error: Incompatible types in assignment (expression has type "Callable[[str], None]", base class "B" defined the type as "Callable[[int], None]")
4768
4769 [case testClassSpec]
4770 from typing import Callable
4771 class A():
4772 b: Callable[[int], int]
4773 class B(A):
4774 def c(self, a: int) -> int: pass
4775 b = c
4776 reveal_type(A().b) # N: Revealed type is "def (builtins.int) -> builtins.int"
4777 reveal_type(B().b) # N: Revealed type is "def (a: builtins.int) -> builtins.int"
4778
4779 [case testClassSpecError]
4780 from typing import Callable
4781 class A():
4782 b: Callable[[int], int]
4783 class B(A):
4784 def c(self, a: str) -> int: pass
4785 b = c # E: Incompatible types in assignment (expression has type "Callable[[str], int]", base class "A" defined the type as "Callable[[int], int]")
4786
4787 [case testClassStaticMethod]
4788 class A():
4789 @staticmethod
4790 def a(a: int) -> None: pass
4791 class B(A):
4792 @staticmethod
4793 def b(a: str) -> None: pass
4794 a = b
4795 [builtins fixtures/staticmethod.pyi]
4796 [out]
4797 main:7: error: Incompatible types in assignment (expression has type "Callable[[str], None]", base class "A" defined the type as "Callable[[int], None]")
4798
4799 [case testClassStaticMethodIndirect]
4800 class A():
4801 @staticmethod
4802 def a(a: int) -> None: pass
4803 c = a
4804 class B(A):
4805 @staticmethod
4806 def b(a: str) -> None: pass
4807 c = b # E: Incompatible types in assignment (expression has type "Callable[[str], None]", base class "A" defined the type as "Callable[[int], None]")
4808 a: A
4809 reveal_type(a.a) # N: Revealed type is "def (a: builtins.int)"
4810 reveal_type(a.c) # N: Revealed type is "def (a: builtins.int)"
4811 [builtins fixtures/staticmethod.pyi]
4812
4813 [case testClassStaticMethodIndirectOverloaded]
4814 from typing import overload
4815 class A:
4816 @overload
4817 @staticmethod
4818 def a(x: int) -> int: ...
4819 @overload
4820 @staticmethod
4821 def a(x: str) -> str: ...
4822 @staticmethod
4823 def a(x):
4824 ...
4825 c = a
4826 reveal_type(A.c) # N: Revealed type is "Overload(def (x: builtins.int) -> builtins.int, def (x: builtins.str) -> builtins.str)"
4827 reveal_type(A().c) # N: Revealed type is "Overload(def (x: builtins.int) -> builtins.int, def (x: builtins.str) -> builtins.str)"
4828 [builtins fixtures/staticmethod.pyi]
4829
4830 [case testClassStaticMethodSubclassing]
4831 class A:
4832 @staticmethod
4833 def a() -> None: pass
4834
4835 def b(self) -> None: pass
4836
4837 @staticmethod
4838 def c() -> None: pass
4839
4840 class B(A):
4841 def a(self) -> None: pass # Fail
4842
4843 @classmethod
4844 def b(cls) -> None: pass
4845
4846 @staticmethod
4847 def c() -> None: pass
4848 [builtins fixtures/classmethod.pyi]
4849 [out]
4850 main:11: error: Signature of "a" incompatible with supertype "A"
4851 main:11: note: Superclass:
4852 main:11: note: @staticmethod
4853 main:11: note: def a() -> None
4854 main:11: note: Subclass:
4855 main:11: note: def a(self) -> None
4856
4857 [case testTempNode]
4858 class A():
4859 def a(self) -> None: pass
4860 class B(A):
4861 def b(self) -> None: pass
4862 a = c = b
4863
4864 [case testListObject]
4865 from typing import List
4866 class A:
4867 x = [] # type: List[object]
4868 class B(A):
4869 x = [1]
4870 [builtins fixtures/list.pyi]
4871
4872 [case testClassMemberObject]
4873 class A:
4874 x = object()
4875 class B(A):
4876 x = 1
4877 class C(B):
4878 x = ''
4879 [out]
4880 main:6: error: Incompatible types in assignment (expression has type "str", base class "B" defined the type as "int")
4881
4882 [case testSlots]
4883 class A:
4884 __slots__ = ("a")
4885 class B(A):
4886 __slots__ = ("a", "b")
4887 [builtins fixtures/tuple.pyi]
4888
4889 [case testClassOrderOfError]
4890 class A:
4891 x = 1
4892 class B(A):
4893 x = "a" # E: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "int")
4894 class C(B):
4895 x = object() # E: Incompatible types in assignment (expression has type "object", base class "B" defined the type as "str")
4896
4897 [case testClassOneErrorPerLine]
4898 class A:
4899 x = 1
4900 class B(A):
4901 x: str = "" # E: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "int")
4902 x = 1.0 # E: Incompatible types in assignment (expression has type "float", variable has type "str")
4903 class BInfer(A):
4904 x = "" # E: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "int")
4905 x = 1.0 # E: Incompatible types in assignment (expression has type "float", variable has type "str") \
4906 # E: Incompatible types in assignment (expression has type "float", base class "A" defined the type as "int")
4907
4908 [case testClassIgnoreType_RedefinedAttributeAndGrandparentAttributeTypesNotIgnored]
4909 class A:
4910 x = 0
4911 class B(A):
4912 x = '' # type: ignore
4913 class C(B):
4914 x = ''
4915
4916 [case testClassIgnoreType_RedefinedAttributeTypeIgnoredInChildren]
4917 class A:
4918 x = 0
4919 class B(A):
4920 x = '' # type: ignore
4921 class C(B):
4922 x = '' # type: ignore
4923
4924 [case testInvalidMetaclassStructure]
4925 class X(type): pass
4926 class Y(type): pass
4927 class A(metaclass=X): pass
4928 class B(A, metaclass=Y): pass # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \
4929 # N: "__main__.Y" (metaclass of "__main__.B") conflicts with "__main__.X" (metaclass of "__main__.A")
4930 [case testMetaclassNoTypeReveal]
4931 class M:
4932 x = 0 # type: int
4933
4934 class A(metaclass=M): pass # E: Metaclasses not inheriting from "type" are not supported
4935
4936 A.x # E: "type[A]" has no attribute "x"
4937
4938 [case testMetaclassTypeReveal]
4939 from typing import Type
4940 class M(type):
4941 x = 0 # type: int
4942
4943 class A(metaclass=M): pass
4944
4945 def f(TA: Type[A]):
4946 reveal_type(TA) # N: Revealed type is "type[__main__.A]"
4947 reveal_type(TA.x) # N: Revealed type is "builtins.int"
4948
4949 [case testMetaclassConflictingInstanceVars]
4950 from typing import ClassVar
4951
4952 class Meta(type):
4953 foo: int
4954 bar: int
4955 eggs: ClassVar[int] = 42
4956 spam: ClassVar[int] = 42
4957
4958 class Foo(metaclass=Meta):
4959 foo: str
4960 bar: ClassVar[str] = 'bar'
4961 eggs: str
4962 spam: ClassVar[str] = 'spam'
4963
4964 reveal_type(Foo.foo) # N: Revealed type is "builtins.int"
4965 reveal_type(Foo.bar) # N: Revealed type is "builtins.str"
4966 reveal_type(Foo.eggs) # N: Revealed type is "builtins.int"
4967 reveal_type(Foo.spam) # N: Revealed type is "builtins.str"
4968
4969 class MetaSub(Meta): ...
4970
4971 class Bar(metaclass=MetaSub):
4972 foo: str
4973 bar: ClassVar[str] = 'bar'
4974 eggs: str
4975 spam: ClassVar[str] = 'spam'
4976
4977 reveal_type(Bar.foo) # N: Revealed type is "builtins.int"
4978 reveal_type(Bar.bar) # N: Revealed type is "builtins.str"
4979 reveal_type(Bar.eggs) # N: Revealed type is "builtins.int"
4980 reveal_type(Bar.spam) # N: Revealed type is "builtins.str"
4981
4982 [case testSubclassMetaclass]
4983 class M1(type):
4984 x = 0
4985 class M2(M1): pass
4986 class C(metaclass=M2):
4987 pass
4988 reveal_type(C.x) # N: Revealed type is "builtins.int"
4989
4990 [case testMetaclassSubclass]
4991 from typing import Type
4992 class M(type):
4993 x = 0 # type: int
4994
4995 class A(metaclass=M): pass
4996 class B(A): pass
4997
4998 def f(TB: Type[B]):
4999 reveal_type(TB) # N: Revealed type is "type[__main__.B]"
5000 reveal_type(TB.x) # N: Revealed type is "builtins.int"
5001
5002 [case testMetaclassAsAny]
5003 from typing import Any, ClassVar, Type
5004
5005 MyAny: Any
5006 class WithMeta(metaclass=MyAny):
5007 x: ClassVar[int]
5008
5009 reveal_type(WithMeta.a) # N: Revealed type is "Any"
5010 reveal_type(WithMeta.m) # N: Revealed type is "Any"
5011 reveal_type(WithMeta.x) # N: Revealed type is "builtins.int"
5012 reveal_type(WithMeta().x) # N: Revealed type is "builtins.int"
5013 WithMeta().m # E: "WithMeta" has no attribute "m"
5014 WithMeta().a # E: "WithMeta" has no attribute "a"
5015 t: Type[WithMeta]
5016 t.unknown # OK
5017
5018 [case testMetaclassAsAnyWithAFlag]
5019 # flags: --disallow-subclassing-any
5020 from typing import Any, ClassVar, Type
5021
5022 MyAny: Any
5023 class WithMeta(metaclass=MyAny): # E: Class cannot use "MyAny" as a metaclass (has type "Any")
5024 x: ClassVar[int]
5025
5026 reveal_type(WithMeta.a) # N: Revealed type is "Any"
5027 reveal_type(WithMeta.m) # N: Revealed type is "Any"
5028 reveal_type(WithMeta.x) # N: Revealed type is "builtins.int"
5029 reveal_type(WithMeta().x) # N: Revealed type is "builtins.int"
5030 WithMeta().m # E: "WithMeta" has no attribute "m"
5031 WithMeta().a # E: "WithMeta" has no attribute "a"
5032 t: Type[WithMeta]
5033 t.unknown # OK
5034
5035 [case testUnpackIterableClassWithOverloadedIter]
5036 from typing import Generic, overload, Iterator, TypeVar, Union
5037
5038 AnyNum = TypeVar('AnyNum', int, float)
5039
5040 class Foo(Generic[AnyNum]):
5041 @overload
5042 def __iter__(self: Foo[int]) -> Iterator[float]: ...
5043 @overload
5044 def __iter__(self: Foo[float]) -> Iterator[int]: ...
5045 def __iter__(self) -> Iterator[Union[float, int]]:
5046 ...
5047
5048 a, b, c = Foo[int]()
5049 reveal_type(a) # N: Revealed type is "builtins.float"
5050 reveal_type(b) # N: Revealed type is "builtins.float"
5051 reveal_type(c) # N: Revealed type is "builtins.float"
5052
5053 x, y = Foo[float]()
5054 reveal_type(x) # N: Revealed type is "builtins.int"
5055 reveal_type(y) # N: Revealed type is "builtins.int"
5056 [builtins fixtures/list.pyi]
5057
5058 [case testUnpackIterableClassWithOverloadedIter2]
5059 from typing import Union, TypeVar, Generic, overload, Iterator
5060
5061 X = TypeVar('X')
5062
5063 class Foo(Generic[X]):
5064 @overload
5065 def __iter__(self: Foo[str]) -> Iterator[int]: ... # type: ignore
5066 @overload
5067 def __iter__(self: Foo[X]) -> Iterator[str]: ...
5068 def __iter__(self) -> Iterator[Union[int, str]]:
5069 ...
5070
5071 a, b, c = Foo[str]()
5072 reveal_type(a) # N: Revealed type is "builtins.int"
5073 reveal_type(b) # N: Revealed type is "builtins.int"
5074 reveal_type(c) # N: Revealed type is "builtins.int"
5075
5076 x, y = Foo[float]()
5077 reveal_type(x) # N: Revealed type is "builtins.str"
5078 reveal_type(y) # N: Revealed type is "builtins.str"
5079 [builtins fixtures/list.pyi]
5080
5081 [case testUnpackIterableRegular]
5082 from typing import TypeVar, Generic, Iterator
5083
5084 X = TypeVar('X')
5085
5086 class Foo(Generic[X]):
5087 def __iter__(self) -> Iterator[X]:
5088 ...
5089
5090 a, b = Foo[int]()
5091 reveal_type(a) # N: Revealed type is "builtins.int"
5092 reveal_type(b) # N: Revealed type is "builtins.int"
5093 [builtins fixtures/list.pyi]
5094
5095 [case testUnpackNotIterableClass]
5096 class Foo: ...
5097
5098 a, b, c = Foo() # E: "Foo" object is not iterable
5099 [builtins fixtures/list.pyi]
5100
5101 [case testMetaclassIterable]
5102 from typing import Iterable, Iterator
5103
5104 class ImplicitMeta(type):
5105 def __iter__(self) -> Iterator[int]: yield 1
5106
5107 class Implicit(metaclass=ImplicitMeta): pass
5108
5109 for _ in Implicit: pass
5110 reveal_type(list(Implicit)) # N: Revealed type is "builtins.list[builtins.int]"
5111
5112 class ExplicitMeta(type, Iterable[int]):
5113 def __iter__(self) -> Iterator[int]: yield 1
5114
5115 class Explicit(metaclass=ExplicitMeta): pass
5116 for _ in Explicit: pass
5117 reveal_type(list(Explicit)) # N: Revealed type is "builtins.list[builtins.int]"
5118
5119 [builtins fixtures/list.pyi]
5120
5121 [case testMetaclassTuple]
5122 from typing import Tuple
5123
5124 class M(Tuple[int]): pass
5125 class C(metaclass=M): pass # E: Invalid metaclass "M"
5126
5127 [builtins fixtures/tuple.pyi]
5128
5129 [case testMetaclassOperatorBeforeReversed]
5130 class X:
5131 def __radd__(self, x: int) -> int: ...
5132
5133 class Meta(type):
5134 def __add__(cls, x: X) -> str: ...
5135
5136 class Concrete(metaclass=Meta):
5137 pass
5138
5139 reveal_type(Concrete + X()) # N: Revealed type is "builtins.str"
5140 Concrete + "hello" # E: Unsupported operand types for + ("type[Concrete]" and "str")
5141
5142 [case testMetaclassOperatorTypeVar]
5143 from typing import Type, TypeVar
5144
5145 class MetaClass(type):
5146 def __mul__(cls, other: int) -> str:
5147 return ""
5148
5149 class Test(metaclass=MetaClass):
5150 pass
5151
5152 S = TypeVar("S", bound=Test)
5153
5154 def f(x: Type[Test]) -> str:
5155 return x * 0
5156 def g(x: Type[S]) -> str:
5157 return reveal_type(x * 0) # N: Revealed type is "builtins.str"
5158
5159 [case testMetaclassGetitem]
5160 import types
5161
5162 class M(type):
5163 def __getitem__(self, key) -> int: return 1
5164
5165 class A(metaclass=M): pass
5166
5167 reveal_type(A[M]) # N: Revealed type is "builtins.int"
5168 [builtins fixtures/tuple.pyi]
5169
5170 [case testMetaclassSelfType]
5171 from typing import TypeVar, Type
5172
5173 class M(type): pass
5174 T = TypeVar('T')
5175
5176 class M1(M):
5177 def foo(cls: Type[T]) -> T: ...
5178
5179 class A(metaclass=M1): pass
5180 reveal_type(A.foo()) # N: Revealed type is "__main__.A"
5181
5182 [case testMetaclassAndSkippedImport]
5183 # flags: --ignore-missing-imports
5184 from missing import M
5185 class A(metaclass=M):
5186 y = 0
5187 reveal_type(A.y) # N: Revealed type is "builtins.int"
5188 reveal_type(A.x) # N: Revealed type is "Any"
5189
5190 [case testValidTypeAliasAsMetaclass]
5191 from typing_extensions import TypeAlias
5192
5193 Explicit: TypeAlias = type
5194 Implicit = type
5195
5196 class E(metaclass=Explicit): ...
5197 class I(metaclass=Implicit): ...
5198 [builtins fixtures/classmethod.pyi]
5199
5200 [case testValidTypeAliasOfTypeAliasAsMetaclass]
5201 from typing_extensions import TypeAlias
5202
5203 Explicit: TypeAlias = type
5204 Implicit = type
5205
5206 A1: TypeAlias = Explicit
5207 A2 = Explicit
5208 A3: TypeAlias = Implicit
5209 A4 = Implicit
5210
5211 class C1(metaclass=A1): ...
5212 class C2(metaclass=A2): ...
5213 class C3(metaclass=A3): ...
5214 class C4(metaclass=A4): ...
5215 [builtins fixtures/classmethod.pyi]
5216
5217 [case testTypeAliasWithArgsAsMetaclass]
5218 from typing import Generic, TypeVar
5219 from typing_extensions import TypeAlias
5220
5221 T = TypeVar('T')
5222 class Meta(Generic[T]): ...
5223
5224 Explicit: TypeAlias = Meta[T]
5225 Implicit = Meta[T]
5226
5227 class E(metaclass=Explicit): ... # E: Invalid metaclass "Explicit"
5228 class I(metaclass=Implicit): ... # E: Invalid metaclass "Implicit"
5229 [builtins fixtures/classmethod.pyi]
5230
5231 [case testTypeAliasNonTypeAsMetaclass]
5232 from typing_extensions import TypeAlias
5233
5234 Explicit: TypeAlias = int
5235 Implicit = int
5236
5237 class E(metaclass=Explicit): ... # E: Metaclasses not inheriting from "type" are not supported
5238 class I(metaclass=Implicit): ... # E: Metaclasses not inheriting from "type" are not supported
5239 [builtins fixtures/classmethod.pyi]
5240
5241 [case testInvalidVariableAsMetaclass]
5242 from typing import Any
5243 M = 0 # type: int
5244 MM = 0
5245 class A(metaclass=M): # E: Invalid metaclass "M"
5246 y = 0
5247 class B(metaclass=MM): # E: Invalid metaclass "MM"
5248 y = 0
5249 reveal_type(A.y) # N: Revealed type is "builtins.int"
5250 A.x # E: "type[A]" has no attribute "x"
5251
5252 [case testAnyAsBaseOfMetaclass]
5253 from typing import Any, Type
5254 M = None # type: Any
5255 class MM(M): pass
5256
5257 class A(metaclass=MM):
5258 y = 0
5259 @classmethod
5260 def f(cls) -> None: pass
5261 def g(self) -> None: pass
5262
5263 def h(a: Type[A], b: Type[object]) -> None:
5264 h(a, a)
5265 h(b, a) # E: Argument 1 to "h" has incompatible type "type[object]"; expected "type[A]"
5266 a.f(1) # E: Too many arguments for "f" of "A"
5267 reveal_type(a.y) # N: Revealed type is "builtins.int"
5268
5269 x = A # type: MM
5270 reveal_type(A.y) # N: Revealed type is "builtins.int"
5271 reveal_type(A.x) # N: Revealed type is "Any"
5272 A.f(1) # E: Too many arguments for "f" of "A"
5273 A().g(1) # E: Too many arguments for "g" of "A"
5274 [builtins fixtures/classmethod.pyi]
5275
5276 [case testMetaclassTypeCallable]
5277 class M(type):
5278 x = 5
5279
5280 class A(metaclass=M): pass
5281 reveal_type(type(A).x) # N: Revealed type is "builtins.int"
5282
5283 [case testMetaclassStrictSupertypeOfTypeWithClassmethods]
5284 from typing import Type, TypeVar
5285 TA = TypeVar('TA', bound='A')
5286 TTA = TypeVar('TTA', bound='Type[A]')
5287 TM = TypeVar('TM', bound='M')
5288
5289 class M(type):
5290 def g1(cls: 'Type[A]') -> A: pass # E: The erased type of self "type[__main__.A]" is not a supertype of its class "__main__.M"
5291 def g2(cls: Type[TA]) -> TA: pass # E: The erased type of self "type[__main__.A]" is not a supertype of its class "__main__.M"
5292 def g3(cls: TTA) -> TTA: pass # E: The erased type of self "type[__main__.A]" is not a supertype of its class "__main__.M"
5293 def g4(cls: TM) -> TM: pass
5294 m: M
5295
5296 class A(metaclass=M):
5297 def foo(self): pass
5298
5299 reveal_type(A.g1) # N: Revealed type is "def () -> __main__.A"
5300 reveal_type(A.g2) # N: Revealed type is "def () -> __main__.A"
5301 reveal_type(A.g3) # N: Revealed type is "def () -> def () -> __main__.A"
5302 reveal_type(A.g4) # N: Revealed type is "def () -> def () -> __main__.A"
5303
5304 class B(metaclass=M):
5305 def foo(self): pass
5306
5307 B.g1 # E: Invalid self argument "type[B]" to attribute function "g1" with type "Callable[[type[A]], A]"
5308 B.g2 # E: Invalid self argument "type[B]" to attribute function "g2" with type "Callable[[type[TA]], TA]"
5309 B.g3 # E: Invalid self argument "type[B]" to attribute function "g3" with type "Callable[[TTA], TTA]"
5310 reveal_type(B.g4) # N: Revealed type is "def () -> def () -> __main__.B"
5311
5312 # 4 examples of unsoundness - instantiation, classmethod, staticmethod and ClassVar:
5313
5314 ta: Type[A] = m # E: Incompatible types in assignment (expression has type "M", variable has type "type[A]")
5315 a: A = ta()
5316 reveal_type(ta.g1) # N: Revealed type is "def () -> __main__.A"
5317 reveal_type(ta.g2) # N: Revealed type is "def () -> __main__.A"
5318 reveal_type(ta.g3) # N: Revealed type is "def () -> type[__main__.A]"
5319 reveal_type(ta.g4) # N: Revealed type is "def () -> type[__main__.A]"
5320
5321 x: M = ta
5322 x.g1 # E: Invalid self argument "M" to attribute function "g1" with type "Callable[[type[A]], A]"
5323 x.g2 # E: Invalid self argument "M" to attribute function "g2" with type "Callable[[type[TA]], TA]"
5324 x.g3 # E: Invalid self argument "M" to attribute function "g3" with type "Callable[[TTA], TTA]"
5325 reveal_type(x.g4) # N: Revealed type is "def () -> __main__.M"
5326
5327 def r(ta: Type[TA], tta: TTA) -> None:
5328 x: M = ta
5329 y: M = tta
5330
5331 class Class(metaclass=M):
5332 @classmethod
5333 def f1(cls: Type[Class]) -> None: pass
5334 @classmethod
5335 def f2(cls: M) -> None: pass
5336 cl: Type[Class] = m # E: Incompatible types in assignment (expression has type "M", variable has type "type[Class]")
5337 reveal_type(cl.f1) # N: Revealed type is "def ()"
5338 reveal_type(cl.f2) # N: Revealed type is "def ()"
5339 x1: M = cl
5340
5341 class Static(metaclass=M):
5342 @staticmethod
5343 def f() -> None: pass
5344 s: Type[Static] = m # E: Incompatible types in assignment (expression has type "M", variable has type "type[Static]")
5345 reveal_type(s.f) # N: Revealed type is "def ()"
5346 x2: M = s
5347
5348 from typing import ClassVar
5349 class Cvar(metaclass=M):
5350 x = 1 # type: ClassVar[int]
5351 cv: Type[Cvar] = m # E: Incompatible types in assignment (expression has type "M", variable has type "type[Cvar]")
5352 cv.x
5353 x3: M = cv
5354
5355 [builtins fixtures/classmethod.pyi]
5356
5357 [case testMetaclassOverloadResolution]
5358 from typing import Type, overload
5359 class A: pass
5360
5361 class EM(type): pass
5362 class E(metaclass=EM): pass
5363
5364 class EM1(type): pass
5365 class E1(metaclass=EM1): pass
5366
5367 @overload
5368 def f(x: EM) -> int: ...
5369 @overload
5370 def f(x: EM1) -> A: ...
5371 @overload
5372 def f(x: str) -> str: ...
5373 def f(x: object) -> object: return ''
5374
5375 e: EM
5376 reveal_type(f(e)) # N: Revealed type is "builtins.int"
5377
5378 et: Type[E]
5379 reveal_type(f(et)) # N: Revealed type is "builtins.int"
5380
5381 e1: EM1
5382 reveal_type(f(e1)) # N: Revealed type is "__main__.A"
5383
5384 e1t: Type[E1]
5385 reveal_type(f(e1t)) # N: Revealed type is "__main__.A"
5386
5387 reveal_type(f('')) # N: Revealed type is "builtins.str"
5388
5389 [case testTypeCErasesGenericsFromC]
5390 from typing import Generic, Type, TypeVar
5391
5392 K = TypeVar('K')
5393 V = TypeVar('V')
5394 class ExampleDict(Generic[K, V]): ...
5395
5396 D = TypeVar('D')
5397 def mkdict(dict_type: Type[D]) -> D: ...
5398 reveal_type(mkdict(ExampleDict)) # N: Revealed type is "__main__.ExampleDict[Any, Any]"
5399
5400 [case testTupleForwardBase]
5401 from m import a
5402 a[0]() # E: "int" not callable
5403
5404 [file m.py]
5405 from typing import Tuple
5406 a: A
5407 class A(Tuple[int, str]): pass
5408 [builtins fixtures/tuple.pyi]
5409
5410 -- Synthetic types crashes
5411 -- -----------------------
5412
5413 [case testCrashOnSelfRecursiveNamedTupleVar]
5414 from typing import NamedTuple
5415
5416 def test() -> None:
5417 N = NamedTuple('N', [('x', N)]) # E: Cannot resolve name "N" (possible cyclic definition) \
5418 # N: Recursive types are not allowed at function scope
5419 n: N
5420 reveal_type(n) # N: Revealed type is "tuple[Any, fallback=__main__.N@4]"
5421 [builtins fixtures/tuple.pyi]
5422
5423 [case testCrashOnSelfRecursiveTypedDictVar]
5424 from typing import TypedDict
5425
5426 A = TypedDict('A', {'a': 'A'}) # type: ignore
5427 a: A
5428 [builtins fixtures/isinstancelist.pyi]
5429 [typing fixtures/typing-typeddict.pyi]
5430
5431 [case testCrashInJoinOfSelfRecursiveNamedTuples]
5432
5433 from typing import NamedTuple
5434
5435 class N(NamedTuple):
5436 x: N # type: ignore
5437 class M(NamedTuple):
5438 x: M # type: ignore
5439
5440 n: N
5441 m: M
5442 lst = [n, m]
5443 [builtins fixtures/isinstancelist.pyi]
5444
5445 [case testCorrectJoinOfSelfRecursiveTypedDicts]
5446 from typing import TypedDict
5447
5448 def test() -> None:
5449 class N(TypedDict):
5450 x: N # E: Cannot resolve name "N" (possible cyclic definition) \
5451 # N: Recursive types are not allowed at function scope
5452 class M(TypedDict):
5453 x: M # E: Cannot resolve name "M" (possible cyclic definition) \
5454 # N: Recursive types are not allowed at function scope
5455
5456 n: N
5457 m: M
5458 lst = [n, m]
5459 reveal_type(lst[0]['x']) # N: Revealed type is "Any"
5460 [builtins fixtures/isinstancelist.pyi]
5461 [typing fixtures/typing-typeddict.pyi]
5462
5463 [case testCrashInForwardRefToNamedTupleWithIsinstance]
5464 from typing import Dict, NamedTuple
5465
5466 NameDict = Dict[str, 'NameInfo']
5467 class NameInfo(NamedTuple):
5468 ast: bool
5469
5470 def parse_ast(name_dict: NameDict) -> None:
5471 if isinstance(name_dict[''], int):
5472 pass
5473 reveal_type(name_dict['test']) # N: Revealed type is "tuple[builtins.bool, fallback=__main__.NameInfo]"
5474 [builtins fixtures/isinstancelist.pyi]
5475 [typing fixtures/typing-medium.pyi]
5476
5477 [case testCrashInForwardRefToTypedDictWithIsinstance]
5478 from typing import Dict, TypedDict
5479
5480 NameDict = Dict[str, 'NameInfo']
5481 class NameInfo(TypedDict):
5482 ast: bool
5483
5484 def parse_ast(name_dict: NameDict) -> None:
5485 if isinstance(name_dict[''], int):
5486 pass
5487 reveal_type(name_dict['']['ast']) # N: Revealed type is "builtins.bool"
5488 [builtins fixtures/isinstancelist.pyi]
5489 [typing fixtures/typing-typeddict.pyi]
5490
5491 [case testCorrectIsinstanceInForwardRefToNewType]
5492 from typing import Dict, NewType
5493
5494 NameDict = Dict[str, 'NameInfo']
5495 class Base:
5496 ast: bool
5497 NameInfo = NewType('NameInfo', Base)
5498
5499 def parse_ast(name_dict: NameDict) -> None:
5500 if isinstance(name_dict[''], int):
5501 pass
5502 x = name_dict['']
5503 reveal_type(x) # N: Revealed type is "__main__.NameInfo"
5504 if int():
5505 x = NameInfo(Base()) # OK
5506 x = Base() # E: Incompatible types in assignment (expression has type "Base", variable has type "NameInfo")
5507 [builtins fixtures/isinstancelist.pyi]
5508 [typing fixtures/typing-medium.pyi]
5509
5510 [case testNoCrashForwardRefToBrokenDoubleNewType]
5511 from typing import Any, Dict, List, NewType
5512
5513 Foo = NewType('NotFoo', int) # E: String argument 1 "NotFoo" to NewType(...) does not match variable name "Foo"
5514 Foos = NewType('Foos', List[Foo]) # type: ignore
5515
5516 def frob(foos: Dict[Any, Foos]) -> None:
5517 foo = foos.get(1)
5518 assert foo
5519 dict(foo)
5520 [builtins fixtures/dict.pyi]
5521 [out]
5522
5523 [case testNoCrashForwardRefToBrokenDoubleNewTypeClass]
5524 from typing import Any, Dict, List, NewType
5525
5526 Foo = NewType('NotFoo', int) # type: ignore
5527 Foos = NewType('Foos', List[Foo]) # type: ignore
5528
5529 x: C
5530 class C:
5531 def frob(self, foos: Dict[Any, Foos]) -> None:
5532 foo = foos.get(1)
5533 assert foo
5534 dict(foo)
5535
5536 reveal_type(x.frob) # N: Revealed type is "def (foos: builtins.dict[Any, __main__.Foos])"
5537 [builtins fixtures/dict.pyi]
5538 [out]
5539
5540 [case testNewTypeFromForwardNamedTuple]
5541 from typing import NewType, NamedTuple, Tuple
5542
5543 NT = NewType('NT', 'N')
5544 class N(NamedTuple):
5545 x: int
5546
5547 x: NT = N(1) # E: Incompatible types in assignment (expression has type "N", variable has type "NT")
5548 x = NT(N(1))
5549 [builtins fixtures/tuple.pyi]
5550 [out]
5551
5552 [case testNewTypeFromForwardTypedDict]
5553
5554 from typing import NewType, Tuple, TypedDict
5555
5556 NT = NewType('NT', 'N') # E: Argument 2 to NewType(...) must be subclassable (got "N")
5557 class N(TypedDict):
5558 x: int
5559 [builtins fixtures/dict.pyi]
5560 [typing fixtures/typing-typeddict.pyi]
5561 [out]
5562
5563 [case testCorrectAttributeInForwardRefToNamedTuple]
5564 from typing import NamedTuple
5565 proc: Process
5566 reveal_type(proc.state) # N: Revealed type is "builtins.int"
5567
5568 def get_state(proc: 'Process') -> int:
5569 return proc.state
5570 class Process(NamedTuple):
5571 state: int
5572 [builtins fixtures/tuple.pyi]
5573 [out]
5574
5575 [case testCorrectItemTypeInForwardRefToTypedDict]
5576 from typing import TypedDict
5577 proc: Process
5578 reveal_type(proc['state']) # N: Revealed type is "builtins.int"
5579
5580 def get_state(proc: 'Process') -> int:
5581 return proc['state']
5582 class Process(TypedDict):
5583 state: int
5584 [builtins fixtures/isinstancelist.pyi]
5585 [typing fixtures/typing-typeddict.pyi]
5586 [out]
5587
5588 [case testCorrectDoubleForwardNamedTuple]
5589 from typing import NamedTuple
5590
5591 x: A
5592 class A(NamedTuple):
5593 one: 'B'
5594 other: int
5595 class B(NamedTuple):
5596 attr: str
5597 y: A
5598 y = x
5599 reveal_type(x.one.attr) # N: Revealed type is "builtins.str"
5600 [builtins fixtures/tuple.pyi]
5601 [out]
5602
5603 [case testCrashOnDoubleForwardTypedDict]
5604 from typing import TypedDict
5605
5606 x: A
5607 class A(TypedDict):
5608 one: 'B'
5609 other: int
5610 class B(TypedDict):
5611 attr: str
5612
5613 reveal_type(x['one']['attr']) # N: Revealed type is "builtins.str"
5614 [builtins fixtures/isinstancelist.pyi]
5615 [typing fixtures/typing-typeddict.pyi]
5616 [out]
5617
5618 [case testCrashOnForwardUnionOfNamedTuples]
5619 from typing import Union, NamedTuple
5620
5621 Node = Union['Foo', 'Bar']
5622 class Foo(NamedTuple):
5623 x: int
5624 class Bar(NamedTuple):
5625 x: int
5626
5627 def foo(node: Node) -> int:
5628 x = node
5629 reveal_type(node) # N: Revealed type is "tuple[builtins.int, fallback=__main__.Foo] | tuple[builtins.int, fallback=__main__.Bar]"
5630 return x.x
5631 [builtins fixtures/tuple.pyi]
5632 [out]
5633
5634 [case testCrashOnForwardUnionOfTypedDicts]
5635 from typing import TypedDict, Union
5636
5637 NodeType = Union['Foo', 'Bar']
5638 class Foo(TypedDict):
5639 x: int
5640 class Bar(TypedDict):
5641 x: int
5642
5643 def foo(node: NodeType) -> int:
5644 x = node
5645 return x['x']
5646 [builtins fixtures/isinstancelist.pyi]
5647 [typing fixtures/typing-typeddict.pyi]
5648 [out]
5649
5650 [case testSupportForwardUnionOfNewTypes]
5651 from typing import Union, NewType
5652 x: Node
5653 reveal_type(x.x) # N: Revealed type is "builtins.int"
5654
5655 class A:
5656 x: int
5657 class B:
5658 x: int
5659
5660 Node = Union['Foo', 'Bar']
5661 Foo = NewType('Foo', A)
5662 Bar = NewType('Bar', B)
5663
5664 def foo(node: Node) -> Node:
5665 x = node
5666 return Foo(A())
5667 [out]
5668
5669 [case testForwardReferencesInNewTypeMRORecomputed]
5670 from typing import NewType
5671 x: Foo
5672 Foo = NewType('Foo', 'B')
5673 class A:
5674 x: int
5675 class B(A):
5676 pass
5677
5678 reveal_type(x.x) # N: Revealed type is "builtins.int"
5679 [out]
5680
5681 [case testCrashOnComplexNamedTupleUnionProperty]
5682 from typing import NamedTuple, Union
5683
5684 x: AOrB
5685 AOrB = Union['A', 'B']
5686 class A(NamedTuple):
5687 x: int
5688
5689 class B(object):
5690 def __init__(self, a: AOrB) -> None:
5691 self.a = a
5692 @property
5693 def x(self) -> int:
5694 return self.a.x
5695
5696 reveal_type(x.x) # N: Revealed type is "builtins.int"
5697 [builtins fixtures/property.pyi]
5698 [out]
5699
5700 [case testCorrectIsinstanceWithForwardUnion]
5701 from typing import Union, NamedTuple
5702
5703 ForwardUnion = Union['TP', int]
5704 class TP(NamedTuple('TP', [('x', int)])): pass
5705
5706 def f(x: ForwardUnion) -> None:
5707 reveal_type(x) # N: Revealed type is "tuple[builtins.int, fallback=__main__.TP] | builtins.int"
5708 if isinstance(x, TP):
5709 reveal_type(x) # N: Revealed type is "tuple[builtins.int, fallback=__main__.TP]"
5710 [builtins fixtures/isinstance.pyi]
5711 [out]
5712
5713 [case testCrashInvalidArgsSyntheticClassSyntax]
5714 from typing import List, NamedTuple, TypedDict
5715 class TD(TypedDict):
5716 x: List[int, str] # E: "list" expects 1 type argument, but 2 given
5717 class NM(NamedTuple):
5718 x: List[int, str] # E: "list" expects 1 type argument, but 2 given
5719
5720 # These two should never crash, reveals are in the next test
5721 TD({'x': []})
5722 NM(x=[])
5723 [builtins fixtures/dict.pyi]
5724 [typing fixtures/typing-typeddict.pyi]
5725 [out]
5726
5727 [case testCrashInvalidArgsSyntheticClassSyntaxReveals]
5728 from typing import List, NamedTuple, TypedDict
5729 class TD(TypedDict):
5730 x: List[int, str] # E: "list" expects 1 type argument, but 2 given
5731 class NM(NamedTuple):
5732 x: List[int, str] # E: "list" expects 1 type argument, but 2 given
5733
5734 x: TD
5735 x1 = TD({'x': []})
5736 y: NM
5737 y1 = NM(x=[])
5738 reveal_type(x) # N: Revealed type is "TypedDict('__main__.TD', {'x': builtins.list[Any]})"
5739 reveal_type(x1) # N: Revealed type is "TypedDict('__main__.TD', {'x': builtins.list[Any]})"
5740 reveal_type(y) # N: Revealed type is "tuple[builtins.list[Any], fallback=__main__.NM]"
5741 reveal_type(y1) # N: Revealed type is "tuple[builtins.list[Any], fallback=__main__.NM]"
5742 [builtins fixtures/dict.pyi]
5743 [typing fixtures/typing-typeddict.pyi]
5744 [out]
5745
5746 [case testCrashInvalidArgsSyntheticFunctionSyntax]
5747 from typing import List, NewType, NamedTuple, TypedDict
5748 TD = TypedDict('TD', {'x': List[int, str]}) # E: "list" expects 1 type argument, but 2 given
5749 NM = NamedTuple('NM', [('x', List[int, str])]) # E: "list" expects 1 type argument, but 2 given
5750 NT = NewType('NT', List[int, str]) # E: "list" expects 1 type argument, but 2 given
5751
5752 # These three should not crash
5753 TD({'x': []})
5754 NM(x=[])
5755 NT([])
5756 [builtins fixtures/dict.pyi]
5757 [typing fixtures/typing-typeddict.pyi]
5758 [out]
5759
5760 [case testCrashForwardSyntheticClassSyntax]
5761 from typing import NamedTuple, TypedDict
5762 class A1(NamedTuple):
5763 b: 'B'
5764 x: int
5765 class A2(TypedDict):
5766 b: 'B'
5767 x: int
5768 class B:
5769 pass
5770 x: A1
5771 y: A2
5772 reveal_type(x.b) # N: Revealed type is "__main__.B"
5773 reveal_type(y['b']) # N: Revealed type is "__main__.B"
5774 [builtins fixtures/dict.pyi]
5775 [typing fixtures/typing-typeddict.pyi]
5776 [out]
5777
5778 [case testCrashForwardSyntheticFunctionSyntax]
5779 from typing import NamedTuple, TypedDict
5780 A1 = NamedTuple('A1', [('b', 'B'), ('x', int)])
5781 A2 = TypedDict('A2', {'b': 'B', 'x': int})
5782 class B:
5783 pass
5784 x: A1
5785 y: A2
5786 reveal_type(x.b) # N: Revealed type is "__main__.B"
5787 reveal_type(y['b']) # N: Revealed type is "__main__.B"
5788 [builtins fixtures/dict.pyi]
5789 [typing fixtures/typing-typeddict.pyi]
5790 [out]
5791
5792 -- Special support for six
5793 -- -----------------------
5794
5795 [case testSixMetaclass]
5796 import six
5797 class M(type):
5798 x = 5
5799 class A(six.with_metaclass(M)): pass
5800 @six.add_metaclass(M)
5801 class B: pass
5802 reveal_type(type(A).x) # N: Revealed type is "builtins.int"
5803 reveal_type(type(B).x) # N: Revealed type is "builtins.int"
5804 [builtins fixtures/tuple.pyi]
5805
5806 [case testFromSixMetaclass]
5807 from six import with_metaclass, add_metaclass
5808 class M(type):
5809 x = 5
5810 class A(with_metaclass(M)): pass
5811 @add_metaclass(M)
5812 class B: pass
5813 reveal_type(type(A).x) # N: Revealed type is "builtins.int"
5814 reveal_type(type(B).x) # N: Revealed type is "builtins.int"
5815 [builtins fixtures/tuple.pyi]
5816
5817 [case testSixMetaclassImportFrom]
5818 import six
5819 from metadefs import M
5820 class A(six.with_metaclass(M)): pass
5821 @six.add_metaclass(M)
5822 class B: pass
5823 reveal_type(type(A).x) # N: Revealed type is "builtins.int"
5824 reveal_type(type(B).x) # N: Revealed type is "builtins.int"
5825 [file metadefs.py]
5826 class M(type):
5827 x = 5
5828 [builtins fixtures/tuple.pyi]
5829
5830 [case testSixMetaclassImport]
5831 import six
5832 import metadefs
5833 class A(six.with_metaclass(metadefs.M)): pass
5834 @six.add_metaclass(metadefs.M)
5835 class B: pass
5836 reveal_type(type(A).x) # N: Revealed type is "builtins.int"
5837 reveal_type(type(B).x) # N: Revealed type is "builtins.int"
5838 [file metadefs.py]
5839 class M(type):
5840 x = 5
5841 [builtins fixtures/tuple.pyi]
5842
5843 [case testSixMetaclassAndBase]
5844 from typing import Iterable, Iterator
5845 import six
5846 class M(type, Iterable[int]):
5847 x = 5
5848 def __iter__(self) -> Iterator[int]: ...
5849 class A:
5850 def foo(self): pass
5851 class B:
5852 def bar(self): pass
5853 class C1(six.with_metaclass(M, A)): pass
5854 @six.add_metaclass(M)
5855 class D1(A): pass
5856 class C2(six.with_metaclass(M, A, B)): pass
5857 @six.add_metaclass(M)
5858 class D2(A, B): pass
5859 reveal_type(type(C1).x) # N: Revealed type is "builtins.int"
5860 reveal_type(type(D1).x) # N: Revealed type is "builtins.int"
5861 reveal_type(type(C2).x) # N: Revealed type is "builtins.int"
5862 reveal_type(type(D2).x) # N: Revealed type is "builtins.int"
5863 C1().foo()
5864 D1().foo()
5865 C1().bar() # E: "C1" has no attribute "bar"
5866 D1().bar() # E: "D1" has no attribute "bar"
5867 for x in C1: reveal_type(x) # N: Revealed type is "builtins.int"
5868 for x in C2: reveal_type(x) # N: Revealed type is "builtins.int"
5869 C2().foo()
5870 D2().foo()
5871 C2().bar()
5872 D2().bar()
5873 C2().baz() # E: "C2" has no attribute "baz"
5874 D2().baz() # E: "D2" has no attribute "baz"
5875 [builtins fixtures/tuple.pyi]
5876
5877 [case testSixMetaclassGenerics]
5878 from typing import Generic, GenericMeta, TypeVar
5879 import six
5880 class DestroyableMeta(type):
5881 pass
5882 class Destroyable(six.with_metaclass(DestroyableMeta)):
5883 pass
5884 T_co = TypeVar('T_co', bound='Destroyable', covariant=True)
5885 class ArcMeta(GenericMeta, DestroyableMeta):
5886 pass
5887 class Arc(six.with_metaclass(ArcMeta, Generic[T_co], Destroyable)):
5888 pass
5889 @six.add_metaclass(ArcMeta)
5890 class Arc1(Generic[T_co], Destroyable):
5891 pass
5892 class MyDestr(Destroyable):
5893 pass
5894 reveal_type(Arc[MyDestr]()) # N: Revealed type is "__main__.Arc[__main__.MyDestr]"
5895 reveal_type(Arc1[MyDestr]()) # N: Revealed type is "__main__.Arc1[__main__.MyDestr]"
5896 [builtins fixtures/bool.pyi]
5897 [typing fixtures/typing-full.pyi]
5898
5899 [case testSixMetaclassErrors]
5900
5901 import six
5902 class M(type): pass
5903 class A(object): pass
5904 def f() -> type: return M
5905 class C1(six.with_metaclass(M), object): pass # E: Unsupported dynamic base class "six.with_metaclass"
5906 class C2(C1, six.with_metaclass(M)): pass # E: Unsupported dynamic base class "six.with_metaclass"
5907 class C3(six.with_metaclass(A)): pass # E: Metaclasses not inheriting from "type" are not supported
5908 @six.add_metaclass(A) # E: Metaclasses not inheriting from "type" are not supported \
5909 # E: Argument 1 to "add_metaclass" has incompatible type "type[A]"; expected "type[type]"
5910
5911 class D3(A): pass
5912 class C4(six.with_metaclass(M), metaclass=M): pass # E: Multiple metaclass definitions
5913 @six.add_metaclass(M)
5914 class D4(metaclass=M): pass # E: Multiple metaclass definitions
5915 class C5(six.with_metaclass(f())): pass # E: Dynamic metaclass not supported for "C5"
5916 @six.add_metaclass(f()) # E: Dynamic metaclass not supported for "D5"
5917 class D5: pass
5918
5919 @six.add_metaclass(M)
5920 class CD(six.with_metaclass(M)): pass # E: Multiple metaclass definitions
5921
5922 class M1(type): pass
5923 class Q1(metaclass=M1): pass
5924 @six.add_metaclass(M)
5925 class CQA(Q1): pass # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \
5926 # N: "__main__.M" (metaclass of "__main__.CQA") conflicts with "__main__.M1" (metaclass of "__main__.Q1")
5927 class CQW(six.with_metaclass(M, Q1)): pass # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \
5928 # N: "__main__.M" (metaclass of "__main__.CQW") conflicts with "__main__.M1" (metaclass of "__main__.Q1")
5929 [builtins fixtures/tuple.pyi]
5930
5931 [case testSixMetaclassAny]
5932 import t # type: ignore
5933 import six
5934 class E(metaclass=t.M): pass
5935 class F(six.with_metaclass(t.M)): pass
5936 @six.add_metaclass(t.M)
5937 class G: pass
5938 [builtins fixtures/tuple.pyi]
5939
5940 [case testSixMetaclassGenericBase]
5941 import six
5942 import abc
5943 from typing import TypeVar, Generic
5944
5945 T = TypeVar("T")
5946
5947 class C(six.with_metaclass(abc.ABCMeta, Generic[T])):
5948 pass
5949 class D(six.with_metaclass(abc.ABCMeta, C[T])):
5950 pass
5951 [builtins fixtures/tuple.pyi]
5952
5953 -- Special support for future.utils
5954 -- --------------------------------
5955
5956 [case testFutureMetaclass]
5957 import future.utils
5958 class M(type):
5959 x = 5
5960 class A(future.utils.with_metaclass(M)): pass
5961 reveal_type(type(A).x) # N: Revealed type is "builtins.int"
5962 [builtins fixtures/tuple.pyi]
5963
5964 [case testFromFutureMetaclass]
5965 from future.utils import with_metaclass
5966 class M(type):
5967 x = 5
5968 class A(with_metaclass(M)): pass
5969 reveal_type(type(A).x) # N: Revealed type is "builtins.int"
5970 [builtins fixtures/tuple.pyi]
5971
5972 [case testFutureMetaclassImportFrom]
5973 import future.utils
5974 from metadefs import M
5975 class A(future.utils.with_metaclass(M)): pass
5976 reveal_type(type(A).x) # N: Revealed type is "builtins.int"
5977 [file metadefs.py]
5978 class M(type):
5979 x = 5
5980 [builtins fixtures/tuple.pyi]
5981
5982 [case testFutureMetaclassImport]
5983 import future.utils
5984 import metadefs
5985 class A(future.utils.with_metaclass(metadefs.M)): pass
5986 reveal_type(type(A).x) # N: Revealed type is "builtins.int"
5987 [file metadefs.py]
5988 class M(type):
5989 x = 5
5990 [builtins fixtures/tuple.pyi]
5991
5992 [case testFutureMetaclassAndBase]
5993 from typing import Iterable, Iterator
5994 import future.utils
5995 class M(type, Iterable[int]):
5996 x = 5
5997 def __iter__(self) -> Iterator[int]: ...
5998 class A:
5999 def foo(self): pass
6000 class B:
6001 def bar(self): pass
6002 class C1(future.utils.with_metaclass(M, A)): pass
6003 class C2(future.utils.with_metaclass(M, A, B)): pass
6004 reveal_type(type(C1).x) # N: Revealed type is "builtins.int"
6005 reveal_type(type(C2).x) # N: Revealed type is "builtins.int"
6006 C1().foo()
6007 C1().bar() # E: "C1" has no attribute "bar"
6008 for x in C1: reveal_type(x) # N: Revealed type is "builtins.int"
6009 for x in C2: reveal_type(x) # N: Revealed type is "builtins.int"
6010 C2().foo()
6011 C2().bar()
6012 C2().baz() # E: "C2" has no attribute "baz"
6013 [builtins fixtures/tuple.pyi]
6014
6015 [case testFutureMetaclassGenerics]
6016 from typing import Generic, GenericMeta, TypeVar
6017 import future.utils
6018 class DestroyableMeta(type):
6019 pass
6020 class Destroyable(future.utils.with_metaclass(DestroyableMeta)):
6021 pass
6022 T_co = TypeVar('T_co', bound='Destroyable', covariant=True)
6023 class ArcMeta(GenericMeta, DestroyableMeta):
6024 pass
6025 class Arc(future.utils.with_metaclass(ArcMeta, Generic[T_co], Destroyable)):
6026 pass
6027 class MyDestr(Destroyable):
6028 pass
6029 reveal_type(Arc[MyDestr]()) # N: Revealed type is "__main__.Arc[__main__.MyDestr]"
6030 [builtins fixtures/bool.pyi]
6031 [typing fixtures/typing-full.pyi]
6032
6033 [case testFutureMetaclassErrors]
6034 import future.utils
6035 class M(type): pass
6036 class A(object): pass
6037 def f() -> type: return M
6038 class C1(future.utils.with_metaclass(M), object): pass # E: Unsupported dynamic base class "future.utils.with_metaclass"
6039 class C2(C1, future.utils.with_metaclass(M)): pass # E: Unsupported dynamic base class "future.utils.with_metaclass"
6040 class C3(future.utils.with_metaclass(A)): pass # E: Metaclasses not inheriting from "type" are not supported
6041 class C4(future.utils.with_metaclass(M), metaclass=M): pass # E: Multiple metaclass definitions
6042 class C5(future.utils.with_metaclass(f())): pass # E: Dynamic metaclass not supported for "C5"
6043
6044 class M1(type): pass
6045 class Q1(metaclass=M1): pass
6046 class CQW(future.utils.with_metaclass(M, Q1)): pass # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \
6047 # N: "__main__.M" (metaclass of "__main__.CQW") conflicts with "__main__.M1" (metaclass of "__main__.Q1")
6048 [builtins fixtures/tuple.pyi]
6049
6050 [case testFutureMetaclassAny]
6051 import t # type: ignore
6052 import future.utils
6053 class E(metaclass=t.M): pass
6054 class F(future.utils.with_metaclass(t.M)): pass
6055
6056 -- Misc
6057 -- ----
6058 [builtins fixtures/tuple.pyi]
6059
6060 [case testCorrectEnclosingClassPushedInDeferred]
6061 class C:
6062 def __getattr__(self, attr: str) -> int:
6063 x: F
6064 return x.f
6065
6066 class F:
6067 def __init__(self, f: int) -> None:
6068 self.f = f
6069 [out]
6070
6071 [case testCorrectEnclosingClassPushedInDeferred2]
6072 from typing import TypeVar
6073 T = TypeVar('T', bound='C')
6074 class C:
6075 def m(self: T) -> T:
6076 class Inner:
6077 x: F
6078 f = x.f
6079 return self
6080
6081 class F:
6082 def __init__(self, f: int) -> None:
6083 self.f = f
6084 [out]
6085
6086 [case testCorrectEnclosingClassPushedInDeferred3]
6087 class A:
6088 def f(self) -> None:
6089 def g(x: int) -> int:
6090 return y
6091
6092 y = int()
6093 [out]
6094
6095 [case testMetaclassMemberAccessViaType]
6096 from typing import Type
6097 class M(type):
6098 def m(cls, x: int) -> int:
6099 pass
6100
6101 class C(metaclass=M):
6102 pass
6103 x = C
6104 y: Type[C] = C
6105
6106 reveal_type(type(C).m) # N: Revealed type is "def (cls: __main__.M, x: builtins.int) -> builtins.int"
6107 reveal_type(type(x).m) # N: Revealed type is "def (cls: __main__.M, x: builtins.int) -> builtins.int"
6108 reveal_type(type(y).m) # N: Revealed type is "def (cls: __main__.M, x: builtins.int) -> builtins.int"
6109 [out]
6110
6111 [case testMetaclassMemberAccessViaType2]
6112 from typing import Any, Type
6113 class M(type):
6114 def m(cls, x: int) -> int:
6115 pass
6116 B: Any
6117 class C(B, metaclass=M):
6118 pass
6119
6120 x: Type[C]
6121 reveal_type(x.m) # N: Revealed type is "def (x: builtins.int) -> builtins.int"
6122 reveal_type(x.whatever) # N: Revealed type is "Any"
6123 [out]
6124
6125 [case testMetaclassMemberAccessViaType3]
6126 from typing import Any, Type, TypeVar
6127 T = TypeVar('T')
6128 class C(Any):
6129 def bar(self: T) -> Type[T]: pass
6130 def foo(self) -> None:
6131 reveal_type(self.bar()) # N: Revealed type is "type[__main__.C]"
6132 reveal_type(self.bar().__name__) # N: Revealed type is "builtins.str"
6133 [builtins fixtures/type.pyi]
6134 [out]
6135
6136 [case testClassDecoratorIsTypeChecked]
6137 from typing import Callable, Type
6138 def decorate(x: int) -> Callable[[type], type]:
6139 ...
6140 def decorate_forward_ref() -> Callable[[Type[A]], Type[A]]:
6141 ...
6142 @decorate(y=17) # E: Unexpected keyword argument "y" for "decorate"
6143 @decorate() # E: Missing positional argument "x" in call to "decorate"
6144 @decorate(22, 25) # E: Too many arguments for "decorate"
6145 @decorate_forward_ref()
6146 @decorate(11)
6147 class A: pass
6148
6149 @decorate # E: Argument 1 to "decorate" has incompatible type "type[A2]"; expected "int"
6150 class A2: pass
6151
6152 [case testClassDecoratorIncorrect]
6153 def not_a_class_decorator(x: int) -> int: ...
6154 @not_a_class_decorator(7)
6155 class A3: pass # E: "int" not callable
6156
6157 not_a_function = 17
6158 @not_a_function() # E: "int" not callable
6159 class B: pass
6160
6161 @not_a_function
6162 class B2: pass # E: "int" not callable
6163
6164 b = object()
6165 @b.nothing # E: "object" has no attribute "nothing"
6166 class C: pass
6167
6168 @undefined # E: Name "undefined" is not defined
6169 class D: pass
6170
6171 [case testSlotsCompatibility]
6172 class A:
6173 __slots__ = ()
6174 class B(A):
6175 __slots__ = ('a', 'b')
6176 class C:
6177 __slots__ = ('x',)
6178 class D(B, C): # E: Class "D" has incompatible disjoint bases
6179 __slots__ = ('aa', 'bb', 'cc')
6180 [builtins fixtures/tuple.pyi]
6181
6182 [case testRevealLocalsOnClassVars]
6183 class C1(object):
6184 t = 'a'
6185 y = 3.0
6186 class Inner(object): pass
6187 reveal_locals()
6188
6189 [out]
6190 main:5: note: Revealed local types are:
6191 main:5: note: t: builtins.str
6192 main:5: note: y: builtins.float
6193
6194 [case testAbstractClasses]
6195 import a
6196 import b
6197
6198 [file a.pyi]
6199 from abc import ABCMeta, abstractmethod
6200 from typing import Protocol
6201
6202 class A: # OK, has @abstractmethod
6203 @abstractmethod
6204 def f(self) -> None:
6205 pass
6206
6207 class B(A): # E: Class a.B has abstract attributes "f" # N: If it is meant to be abstract, add 'abc.ABCMeta' as an explicit metaclass
6208 pass
6209
6210 class C(A, metaclass=ABCMeta): # OK, has ABCMeta as a metaclass
6211 pass
6212
6213 class D(A): # OK, implements the abstract method
6214 def f(self) -> None:
6215 pass
6216
6217 class E(Protocol): # OK, is a protocol
6218 @abstractmethod
6219 def f(self) -> None:
6220 pass
6221
6222 class F(E, Protocol): # OK, is a protocol
6223 pass
6224
6225 # Custom metaclass subclassing `ABCMeta`, see #13561
6226 class CustomMeta(ABCMeta):
6227 pass
6228
6229 class G(A, metaclass=CustomMeta): # Ok, has CustomMeta as a metaclass
6230 pass
6231
6232 [file b.py]
6233 # All of these are OK because this is not a stub file.
6234 from abc import ABCMeta, abstractmethod
6235 from typing import Protocol
6236
6237 class A:
6238 @abstractmethod
6239 def f(self) -> None:
6240 pass
6241
6242 class B(A):
6243 pass
6244
6245 class C(A, metaclass=ABCMeta):
6246 pass
6247
6248 class D(A):
6249 def f(self) -> None:
6250 pass
6251
6252 class E(Protocol):
6253 @abstractmethod
6254 def f(self) -> None:
6255 pass
6256
6257 class F(E, Protocol):
6258 pass
6259
6260 class CustomMeta(ABCMeta):
6261 pass
6262
6263 class G(A, metaclass=CustomMeta):
6264 pass
6265
6266 [case testClassMethodOverride]
6267 from typing import Callable, Any
6268
6269 def deco(f: Callable[..., Any]) -> Callable[..., Any]: ...
6270
6271 class B:
6272 @classmethod
6273 def meth(cls, x: int) -> int: ...
6274
6275 class C(B):
6276 @classmethod
6277 @deco
6278 def meth(cls, x: int) -> int: ...
6279 [builtins fixtures/classmethod.pyi]
6280 [out]
6281
6282 [case testGetAttrImportAnnotation]
6283 import a
6284 x: a.A
6285 y: a.A.B.C
6286 reveal_type(x) # N: Revealed type is "Any"
6287 reveal_type(y) # N: Revealed type is "Any"
6288 [file a.pyi]
6289 from typing import Any
6290 def __getattr__(attr: str) -> Any: ...
6291 [builtins fixtures/module.pyi]
6292 [out]
6293
6294 [case testGetAttrImportBaseClass]
6295 import a
6296 class B(a.A): ...
6297 [file a.pyi]
6298 from typing import Any
6299 def __getattr__(attr: str) -> Any: ...
6300 [builtins fixtures/module.pyi]
6301 [out]
6302
6303 [case testGetAttrDescriptor]
6304 from typing import TypeVar, Generic, Any
6305
6306 T = TypeVar('T')
6307 class C(Generic[T]):
6308 normal: T
6309 def __getattr__(self, attr: str) -> T: ...
6310
6311 class Descr:
6312 def __get__(self, inst: Any, owner: Any) -> int: ...
6313
6314 class D(C[Descr]):
6315 other: Descr
6316
6317 d: D
6318 reveal_type(d.normal) # N: Revealed type is "builtins.int"
6319 reveal_type(d.dynamic) # N: Revealed type is "__main__.Descr"
6320 reveal_type(D.other) # N: Revealed type is "builtins.int"
6321 D.dynamic # E: "type[D]" has no attribute "dynamic"
6322 [out]
6323
6324 [case testSelfDescriptorAssign]
6325 from typing import Any
6326
6327 class Descr:
6328 def __get__(self, inst: Any, owner: Any) -> int: ...
6329
6330 class C:
6331 def __init__(self, x: Descr) -> None:
6332 self.x = x
6333
6334 c = C(Descr())
6335 reveal_type(c.x) # N: Revealed type is "__main__.Descr"
6336 [out]
6337
6338 [case testForwardInstanceWithWrongArgCount]
6339 from typing import TypeVar, Generic
6340
6341 T = TypeVar('T')
6342 class G(Generic[T]): ...
6343
6344 A = G
6345 x: A[B[int, int]] # E: "G" expects 1 type argument, but 2 given
6346 B = G
6347 [out]
6348
6349 [case testForwardInstanceWithNoArgs]
6350 from typing import TypeVar, Generic
6351
6352 T = TypeVar('T')
6353 class G(Generic[T]): ...
6354
6355 A = G
6356 x: A[B]
6357 reveal_type(x) # N: Revealed type is "__main__.G[__main__.G[Any]]"
6358 B = G
6359 [out]
6360
6361 [case testForwardInstanceWithBound]
6362 # flags: --show-column-numbers
6363 from typing import TypeVar, Generic
6364
6365 T = TypeVar('T', bound=str)
6366 class G(Generic[T]): ...
6367
6368 A = G
6369 x: A[B[int]] # E
6370 B = G
6371 [out]
6372 main:8:6: error: Type argument "G[int]" of "G" must be a subtype of "str"
6373 main:8:8: error: Type argument "int" of "G" must be a subtype of "str"
6374
6375 [case testExtremeForwardReferencing]
6376 from typing import TypeVar, Generic
6377
6378 T = TypeVar('T', covariant=True)
6379 class B(Generic[T]): ...
6380
6381 y: A
6382 z: A[int]
6383 x = [y, z]
6384 reveal_type(x) # N: Revealed type is "builtins.list[__main__.B[Any]]"
6385
6386 A = B
6387 [builtins fixtures/list.pyi]
6388 [out]
6389
6390 [case testNoneAnyFallback]
6391 from typing import Any
6392 dynamic: Any
6393 class C(dynamic): pass
6394 x: None = C() # E: Incompatible types in assignment (expression has type "C", variable has type "None")
6395 [out]
6396
6397 [case testNoneAnyFallbackDescriptor]
6398 from typing import Any
6399 from d import Descr
6400
6401 dynamic: Any
6402 class C(dynamic):
6403 id = Descr(int)
6404 name = Descr(str)
6405
6406 c: C
6407 reveal_type(c.id) # N: Revealed type is "builtins.int"
6408 reveal_type(C.name) # N: Revealed type is "d.Descr[builtins.str]"
6409
6410 [file d.pyi]
6411 from typing import Any, overload, Generic, TypeVar, Type
6412
6413 T = TypeVar('T')
6414 class Descr(Generic[T]):
6415 def __init__(self, tp: Type[T]) -> None: ...
6416 @overload
6417 def __get__(self, inst: None, owner: Any) -> Descr[T]: ...
6418 @overload
6419 def __get__(self, inst: object, owner: Any) -> T: ...
6420 [out]
6421
6422 [case testClassCustomPropertyWorks]
6423 from typing import TypeVar, Generic, Callable, Any
6424
6425 V = TypeVar('V')
6426
6427 class classproperty(Generic[V]):
6428 def __init__(self, getter: Callable[[Any], V]) -> None:
6429 self.getter = getter
6430 def __get__(self, instance: Any, owner: Any) -> V:
6431 return self.getter(owner)
6432
6433 class C:
6434 @classproperty
6435 def foo(cls) -> int:
6436 return 42
6437
6438 reveal_type(C.foo) # N: Revealed type is "builtins.int"
6439 reveal_type(C().foo) # N: Revealed type is "builtins.int"
6440 [out]
6441
6442 [case testMultipleInheritanceCycle]
6443 import b
6444 [file a.py]
6445 from b import B
6446 class A: ...
6447 class C(A, B): ...
6448 class D(C): ...
6449 class Other: ...
6450 [file b.py]
6451 from a import Other
6452 class B: ...
6453 [out]
6454
6455 [case testMultipleInheritanceCycle2]
6456 import b
6457 [file a.py]
6458 from b import B
6459 class A: ...
6460 class C(A, B): ...
6461 class D(C): ...
6462 class Other: ...
6463 a: A
6464 b: B
6465 c: C
6466 d: D
6467 d = A() # E: Incompatible types in assignment (expression has type "A", variable has type "D")
6468 if int():
6469 d = B() # E: Incompatible types in assignment (expression has type "B", variable has type "D")
6470 if int():
6471 d = C() # E: Incompatible types in assignment (expression has type "C", variable has type "D")
6472 a = D()
6473 b = D()
6474 c = D()
6475 [file b.py]
6476 from a import Other
6477 class B: ...
6478 [out]
6479
6480 [case testAllowPropertyAndInit1]
6481 class C:
6482 def __init__(self, x: int) -> None:
6483 self.x = x
6484 @property
6485 def x(self) -> int: pass
6486 @x.setter
6487 def x(self, x: int) -> None: pass
6488 [builtins fixtures/property.pyi]
6489 [out]
6490
6491 [case testAllowPropertyAndInit2]
6492 class C:
6493 @property
6494 def x(self) -> int: pass
6495 @x.setter
6496 def x(self, x: int) -> None: pass
6497 def __init__(self, x: int) -> None:
6498 self.x = x
6499 [builtins fixtures/property.pyi]
6500
6501 [case testAllowPropertyAndInit3]
6502 class C:
6503 def __init__(self, x: int) -> None:
6504 self.x = x # type: ignore
6505 @property # Should be no error here
6506 def x(self) -> int: pass
6507 [builtins fixtures/property.pyi]
6508 [out]
6509
6510 [case testClassMethodBeforeInit1]
6511 class Foo:
6512 @classmethod
6513 def bar(cls) -> Foo:
6514 return cls("bar")
6515
6516 def __init__(self, baz: str) -> None:
6517 self.baz = baz
6518 [builtins fixtures/classmethod.pyi]
6519
6520 [case testClassMethodBeforeInit2]
6521 class Foo:
6522 @classmethod
6523 def bar(cls) -> Foo:
6524 return cls(Bar())
6525
6526 def __init__(self, baz: 'Bar') -> None:
6527 self.baz = baz
6528
6529 class Bar: pass
6530 [builtins fixtures/classmethod.pyi]
6531
6532 [case testClassMethodBeforeInit3]
6533 from typing import overload
6534 class Foo:
6535 @classmethod
6536 @overload
6537 def bar(cls, x: int) -> Foo: ...
6538 @classmethod
6539 @overload
6540 def bar(cls, x: str) -> Foo: ...
6541 @classmethod
6542 def bar(cls, x: object) -> Foo:
6543 return cls(x)
6544
6545 def __init__(self, baz: object) -> None:
6546 self.baz = baz
6547
6548 [builtins fixtures/classmethod.pyi]
6549
6550 [case testNewAndInit1]
6551 class A:
6552 def __init__(self, x: int) -> None:
6553 pass
6554
6555 class B(A):
6556 def __new__(cls) -> B:
6557 pass
6558
6559 B()
6560
6561 [case testNewAndInit2]
6562 from typing import Any
6563
6564 class A:
6565 def __new__(cls, *args: Any) -> 'A':
6566 ...
6567
6568 class B(A):
6569 def __init__(self, x: int) -> None:
6570 pass
6571
6572 reveal_type(B) # N: Revealed type is "def (x: builtins.int) -> __main__.B"
6573 [builtins fixtures/tuple.pyi]
6574
6575 [case testNewAndInit3]
6576 from typing import Any
6577
6578 class A:
6579 def __new__(cls, *args: Any) -> 'A':
6580 ...
6581 def __init__(self, x: int) -> None:
6582 pass
6583
6584 reveal_type(A) # N: Revealed type is "def (x: builtins.int) -> __main__.A"
6585 [builtins fixtures/tuple.pyi]
6586
6587 [case testCyclicDecorator]
6588 import b
6589 [file a.py]
6590 import b
6591 import c
6592
6593 class A(b.B):
6594 @c.deco
6595 def meth(self) -> int: ...
6596 [file b.py]
6597 import a
6598 import c
6599
6600 class B:
6601 @c.deco
6602 def meth(self) -> int: ...
6603 [file c.py]
6604 from typing import TypeVar, Tuple, Callable
6605 T = TypeVar('T')
6606 def deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...
6607 [builtins fixtures/tuple.pyi]
6608 [out]
6609
6610 [case testCyclicOverload]
6611 import b
6612 [file a.pyi]
6613 import b
6614 from typing import overload
6615
6616 class A(b.B):
6617 @overload
6618 def meth(self, x: int) -> int: ...
6619 @overload
6620 def meth(self, x: str) -> str: ...
6621 [file b.pyi]
6622 import a
6623 from typing import overload
6624
6625 class B:
6626 @overload
6627 def meth(self, x: int) -> int: ...
6628 @overload
6629 def meth(self, x: str) -> str: ...
6630 [out]
6631
6632 [case testCyclicOverloadDeferred]
6633 import b
6634 [file a.py]
6635 import b
6636 from typing import overload, Union
6637
6638 class A(b.B):
6639 @overload
6640 def meth(self, x: int) -> int: ...
6641 @overload
6642 def meth(self, x: str) -> str: ...
6643 def meth(self, x) -> Union[int, str]:
6644 reveal_type(other.x) # N: Revealed type is "builtins.int"
6645 return 0
6646
6647 other: Other
6648 class Other:
6649 def __init__(self) -> None:
6650 self.x = f()
6651 def f() -> int: ...
6652 [file b.py]
6653 import a
6654 from typing import overload
6655
6656 class B:
6657 @overload
6658 def meth(self, x: int) -> int: ...
6659 @overload
6660 def meth(self, x: str) -> str: ...
6661 def meth(self, x):
6662 pass
6663 [out]
6664
6665 [case testCyclicOverrideAny]
6666 import a
6667 [file b.py]
6668 import a
6669 class Sub(a.Base):
6670 def x(self) -> int: pass
6671
6672 [file a.py]
6673 import b
6674 class Base:
6675 def __init__(self):
6676 self.x = 1
6677 [out]
6678
6679 [case testCyclicOverrideChecked]
6680 import a
6681 [file b.py]
6682 import a
6683 class Sub(a.Base):
6684 def x(self) -> int: pass # E: Signature of "x" incompatible with supertype "Base" \
6685 # N: Superclass: \
6686 # N: int \
6687 # N: Subclass: \
6688 # N: def x(self) -> int
6689
6690 [file a.py]
6691 import b
6692 class Base:
6693 def __init__(self) -> None:
6694 self.x = 1
6695 [out]
6696
6697 [case testCyclicOverrideCheckedDecorator]
6698 import a
6699 [file b.py]
6700 import a
6701 import c
6702 class Sub(a.Base):
6703 @c.deco
6704 def x(self) -> int: pass # E: Signature of "x" incompatible with supertype "Base" \
6705 # N: Superclass: \
6706 # N: int \
6707 # N: Subclass: \
6708 # N: def x(*Any, **Any) -> tuple[int, int]
6709
6710 [file a.py]
6711 import b
6712 import c
6713 class Base:
6714 def __init__(self) -> None:
6715 self.x = 1
6716 [file c.py]
6717 from typing import TypeVar, Tuple, Callable
6718 T = TypeVar('T')
6719 def deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...
6720 [builtins fixtures/tuple.pyi]
6721 [out]
6722
6723 [case testCyclicOverrideCheckedDecoratorDeferred]
6724 import a
6725 [file b.py]
6726 import a
6727 import c
6728 class Sub(a.Base):
6729 @c.deco
6730 def x(self) -> int: pass # E: Signature of "x" incompatible with supertype "Base" \
6731 # N: Superclass: \
6732 # N: int \
6733 # N: Subclass: \
6734 # N: def x(*Any, **Any) -> tuple[int, int]
6735
6736 [file a.py]
6737 import b
6738 import c
6739 class Base:
6740 def __init__(self) -> None:
6741 self.x = f()
6742
6743 def f() -> int: ...
6744 [file c.py]
6745 from typing import TypeVar, Tuple, Callable
6746 T = TypeVar('T')
6747 def deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...
6748 [builtins fixtures/tuple.pyi]
6749 [out]
6750
6751 [case testCyclicOverrideAnyDecoratorDeferred]
6752 import a
6753 [file b.py]
6754 import a
6755 import c
6756 class Sub(a.Base):
6757 @c.deco
6758 def x(self) -> int: pass
6759
6760 [file a.py]
6761 from b import Sub
6762 import c
6763 class Base:
6764 def __init__(self) -> None:
6765 self.x = f()
6766
6767 def f() -> int: ...
6768 [file c.py]
6769 from typing import Any, Callable
6770 def deco(f: Callable[..., Any]) -> Any: ...
6771 [out]
6772
6773 [case testCyclicDecoratorDoubleDeferred]
6774 import b
6775 [file a.py]
6776 import b
6777 import c
6778
6779 class A(b.B):
6780 @c.deco
6781 def meth(self) -> int:
6782 reveal_type(other.x) # N: Revealed type is "builtins.int"
6783 return 0
6784
6785 other: Other
6786 class Other:
6787 def __init__(self) -> None:
6788 self.x = f()
6789 def f() -> int: ...
6790 [file b.py]
6791 from a import A
6792 import c
6793
6794 class B:
6795 @c.deco
6796 def meth(self) -> int:
6797 pass
6798 [file c.py]
6799 from typing import TypeVar, Tuple, Callable
6800 T = TypeVar('T')
6801 def deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...
6802 [builtins fixtures/tuple.pyi]
6803 [out]
6804
6805 [case testCyclicDecoratorSuper]
6806 import b
6807 [file a.py]
6808 import b
6809 import c
6810
6811 class A(b.B):
6812 @c.deco
6813 def meth(self) -> int:
6814 y = super().meth()
6815 reveal_type(y) # N: Revealed type is "tuple[builtins.int, builtins.int]"
6816 return 0
6817 [file b.py]
6818 from a import A
6819 import c
6820
6821 class B:
6822 @c.deco
6823 def meth(self) -> int:
6824 pass
6825 [file c.py]
6826 from typing import TypeVar, Tuple, Callable
6827 T = TypeVar('T')
6828 def deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...
6829 [builtins fixtures/tuple.pyi]
6830 [out]
6831
6832 [case testCyclicDecoratorBothDeferred]
6833 import b
6834 [file a.py]
6835 import b
6836 import c
6837
6838 class A(b.B):
6839 @c.deco
6840 def meth(self) -> int:
6841 pass
6842 [file b.py]
6843 from a import A
6844 import c
6845
6846 class B:
6847 @c.deco
6848 def meth(self) -> int:
6849 reveal_type(other.x) # N: Revealed type is "builtins.int"
6850 return 0
6851
6852 other: Other
6853 class Other:
6854 def __init__(self) -> None:
6855 self.x = f()
6856 def f() -> int: ...
6857 [file c.py]
6858 from typing import TypeVar, Tuple, Callable
6859 T = TypeVar('T')
6860 def deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...
6861 [builtins fixtures/tuple.pyi]
6862 [out]
6863
6864 [case testCyclicDecoratorSuperDeferred]
6865 import b
6866 [file a.py]
6867 import b
6868 import c
6869
6870 class A(b.B):
6871 @c.deco
6872 def meth(self) -> int:
6873 y = super().meth()
6874 reveal_type(y) # N: Revealed type is "tuple[builtins.int, builtins.int]"
6875 reveal_type(other.x) # N: Revealed type is "builtins.int"
6876 return 0
6877
6878 other: Other
6879 class Other:
6880 def __init__(self) -> None:
6881 self.x = f()
6882 def f() -> int: ...
6883 [file b.py]
6884 from a import A
6885 import c
6886
6887 class B:
6888 @c.deco
6889 def meth(self) -> int:
6890 pass
6891 [file c.py]
6892 from typing import TypeVar, Tuple, Callable
6893 T = TypeVar('T')
6894 def deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...
6895 [builtins fixtures/tuple.pyi]
6896
6897 [case testOverrideWithUntypedNotChecked]
6898 class Parent:
6899 def foo(self, x):
6900 ...
6901 def bar(self, x):
6902 ...
6903 def baz(self, x: int) -> str:
6904 return ""
6905
6906 class Child(Parent):
6907 def foo(self, y): # OK: names not checked
6908 ...
6909 def bar(self, x, y):
6910 ...
6911 def baz(self, x, y):
6912 return ""
6913 [builtins fixtures/tuple.pyi]
6914
6915 [case testOverrideWithUntypedCheckedWithCheckUntypedDefs]
6916 # flags: --check-untyped-defs
6917 class Parent:
6918 def foo(self, x):
6919 ...
6920 def bar(self, x):
6921 ...
6922 def baz(self, x: int) -> str:
6923 return ""
6924
6925 class Child(Parent):
6926 def foo(self, y): # OK: names not checked
6927 ...
6928 def bar(self, x, y) -> None: # E: Signature of "bar" incompatible with supertype "Parent" \
6929 # N: Superclass: \
6930 # N: def bar(self, x: Any) -> Any \
6931 # N: Subclass: \
6932 # N: def bar(self, x: Any, y: Any) -> None
6933 ...
6934 def baz(self, x, y): # E: Signature of "baz" incompatible with supertype "Parent" \
6935 # N: Superclass: \
6936 # N: def baz(self, x: int) -> str \
6937 # N: Subclass: \
6938 # N: def baz(self, x: Any, y: Any) -> Any
6939 return ""
6940 [builtins fixtures/tuple.pyi]
6941
6942 [case testOptionalDescriptorsBinder]
6943 from typing import Type, TypeVar, Optional
6944 T = TypeVar('T')
6945
6946 class IntDescr:
6947 def __get__(self, obj: T, typ: Type[T]) -> Optional[int]: ...
6948 def __set__(self, obj: T, value: Optional[int]) -> None: ...
6949
6950 class C:
6951 spec = IntDescr()
6952
6953 def meth_spec(self) -> None:
6954 if self.spec is None:
6955 self.spec = 0
6956 reveal_type(self.spec) # N: Revealed type is "builtins.int"
6957 [builtins fixtures/bool.pyi]
6958
6959 [case testUnionDescriptorsBinder]
6960 from typing import Type, TypeVar, Union
6961 T = TypeVar('T')
6962
6963 class A: ...
6964 class B: ...
6965
6966 class UnionDescr:
6967 def __get__(self, obj: T, typ: Type[T]) -> Union[A, B]: ...
6968 def __set__(self, obj: T, value: Union[A, B]) -> None: ...
6969
6970 class C:
6971 spec = UnionDescr()
6972
6973 def meth_spec(self) -> None:
6974 self.spec = A()
6975 reveal_type(self.spec) # N: Revealed type is "__main__.A"
6976 [builtins fixtures/bool.pyi]
6977
6978 [case testSubclassDescriptorsBinder]
6979 from typing import Type, TypeVar, Optional
6980 T = TypeVar('T')
6981
6982 class A: ...
6983 class B(A): ...
6984
6985 class SubDescr:
6986 def __get__(self, obj: T, typ: Type[T]) -> A: ...
6987 def __set__(self, obj: T, value: A) -> None: ...
6988
6989 class C:
6990 spec = SubDescr()
6991
6992 def meth_spec(self) -> None:
6993 self.spec = B()
6994 reveal_type(self.spec) # N: Revealed type is "__main__.B"
6995 [builtins fixtures/bool.pyi]
6996
6997 [case testDecoratedDunderGet]
6998 from typing import Any, Callable, TypeVar, Type
6999
7000 F = TypeVar('F', bound=Callable)
7001 T = TypeVar('T')
7002
7003 def decorator(f: F) -> F:
7004 return f
7005
7006 def change(f: Callable) -> Callable[..., int]:
7007 pass
7008
7009 def untyped(f):
7010 return f
7011
7012 class A: ...
7013
7014 class Descr1:
7015 @decorator
7016 def __get__(self, obj: T, typ: Type[T]) -> A: ...
7017 class Descr2:
7018 @change
7019 def __get__(self, obj: T, typ: Type[T]) -> A: ...
7020 class Descr3:
7021 @untyped
7022 def __get__(self, obj: T, typ: Type[T]) -> A: ...
7023
7024 class C:
7025 spec1 = Descr1()
7026 spec2 = Descr2()
7027 spec3 = Descr3()
7028
7029 c: C
7030 reveal_type(c.spec1) # N: Revealed type is "__main__.A"
7031 reveal_type(c.spec2) # N: Revealed type is "builtins.int"
7032 reveal_type(c.spec3) # N: Revealed type is "Any"
7033 [builtins fixtures/bool.pyi]
7034
7035 [case testDecoratedDunderSet]
7036 from typing import Any, Callable, TypeVar, Type
7037
7038 F = TypeVar('F', bound=Callable)
7039 T = TypeVar('T')
7040
7041 def decorator(f: F) -> F:
7042 return f
7043
7044 def change(f: Callable) -> Callable[[Any, Any, int], None]:
7045 pass
7046
7047 def untyped(f):
7048 return f
7049
7050 class A: ...
7051
7052 class Descr1:
7053 @decorator
7054 def __set__(self, obj: T, value: A) -> None: ...
7055 class Descr2:
7056 @change
7057 def __set__(self, obj: T, value: A) -> None: ...
7058 class Descr3:
7059 @untyped
7060 def __set__(self, obj: T, value: A) -> None: ...
7061
7062 class C:
7063 spec1 = Descr1()
7064 spec2 = Descr2()
7065 spec3 = Descr3()
7066
7067 c: C
7068 c.spec1 = A()
7069 c.spec1 = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "A")
7070 c.spec2 = A() # E: Incompatible types in assignment (expression has type "A", variable has type "int")
7071 c.spec2 = 1
7072 c.spec3 = A()
7073 c.spec3 = 1
7074 [builtins fixtures/bool.pyi]
7075
7076 [case testClassLevelImport]
7077 # flags: --ignore-missing-imports
7078 class Test:
7079 import a
7080 def __init__(self) -> None:
7081 some_module = self.a
7082 [out]
7083
7084 [case testIsInstanceTypeVsMetaclass]
7085 from typing import Type
7086 class Meta(type):
7087 pass
7088 class Thing(metaclass=Meta):
7089 pass
7090
7091 def foo(x: Type[Thing]) -> Type[Thing]:
7092 assert isinstance(x, Meta)
7093 return x
7094 [builtins fixtures/isinstancelist.pyi]
7095
7096 [case testIsInstanceTypeVsUnionOfType]
7097 from typing import Type, Union
7098
7099 class AA: pass
7100 class AB: pass
7101
7102 class M: pass
7103
7104 class A(M, AA): pass
7105 class B(M, AB): pass
7106
7107 AOrB = Union[A, B]
7108
7109 class T(object):
7110 def __init__(self, typ: Type[AOrB] = A) -> None:
7111 assert isinstance(typ, type(M))
7112 self.typ: Type[AOrB] = typ
7113 [builtins fixtures/isinstancelist.pyi]
7114
7115 [case testIsInstanceTypeIsSubclass]
7116 from typing import Union, Type
7117
7118 class C: ...
7119
7120 x: Union[C, Type[C]]
7121
7122 if isinstance(x, type) and issubclass(x, C):
7123 reveal_type(x) # N: Revealed type is "type[__main__.C]"
7124 [builtins fixtures/isinstancelist.pyi]
7125
7126 [case testIsInstanceTypeByAssert]
7127 class A:
7128 x = 42
7129
7130 i: type = A
7131 assert issubclass(i, A)
7132 reveal_type(i.x) # N: Revealed type is "builtins.int"
7133 [builtins fixtures/isinstancelist.pyi]
7134
7135 [case testIsInstanceTypeTypeVar]
7136 from typing import Type, TypeVar, Generic, ClassVar
7137
7138 class Base: ...
7139 class Sub(Base):
7140 other: ClassVar[int]
7141
7142 T = TypeVar('T', bound=Base)
7143
7144 class C(Generic[T]):
7145 def meth(self, cls: Type[T]) -> None:
7146 if not issubclass(cls, Sub):
7147 return
7148 reveal_type(cls) # N: Revealed type is "type[T`1]"
7149 reveal_type(cls.other) # N: Revealed type is "builtins.int"
7150 [builtins fixtures/isinstance.pyi]
7151
7152 [case testIsInstanceTypeSubclass]
7153 from typing import Type, Optional
7154 class Base: ...
7155 class One(Base):
7156 x: int
7157 class Other(Base):
7158 x: int
7159
7160 def test() -> None:
7161 x: Optional[Type[Base]]
7162 if int():
7163 x = One
7164 elif int():
7165 x = Other
7166 else:
7167 return
7168 reveal_type(x) # N: Revealed type is "(def () -> __main__.One) | (def () -> __main__.Other)"
7169 reveal_type(x.x) # N: Revealed type is "builtins.int"
7170 [builtins fixtures/isinstancelist.pyi]
7171
7172 [case testMemberRedefinition]
7173 class C:
7174 def __init__(self) -> None:
7175 self.foo = 12
7176 self.foo: int = 12 # E: Attribute "foo" already defined on line 3
7177
7178 [case testMemberRedefinitionDefinedInClass]
7179 class C:
7180 foo = 12
7181 def __init__(self) -> None:
7182 self.foo: int = 12 # E: Attribute "foo" already defined on line 2
7183
7184 [case testAbstractInit]
7185 from abc import abstractmethod, ABCMeta
7186 class A(metaclass=ABCMeta):
7187 @abstractmethod
7188 def __init__(self, a: int) -> None:
7189 pass
7190 class B(A):
7191 pass
7192 class C(B):
7193 def __init__(self, a: int) -> None:
7194 self.c = a
7195 a = A(1) # E: Cannot instantiate abstract class "A" with abstract attribute "__init__"
7196 A.c # E: "type[A]" has no attribute "c"
7197 b = B(2) # E: Cannot instantiate abstract class "B" with abstract attribute "__init__"
7198 B.c # E: "type[B]" has no attribute "c"
7199 c = C(3)
7200 c.c
7201 C.c # E: Cannot access instance-only attribute "c" on class object
7202
7203 [case testAccessInstanceVarOnClass]
7204 class A:
7205 def __init__(self) -> None:
7206 self.x = 0
7207
7208 A.x # E: Cannot access instance-only attribute "x" on class object
7209 A.x = 1 # We allow this, since it works at runtime, even though it is weird
7210
7211 class B:
7212 x = 1
7213 class C(B):
7214 def __init__(self) -> None:
7215 self.x: int = 2
7216 C.x # Again, this works at runtime, so we don't prohibit this
7217
7218 [case testDecoratedConstructors]
7219 from typing import TypeVar, Callable, Any
7220
7221 F = TypeVar('F', bound=Callable[..., Any])
7222
7223 def dec(f: F) -> F: ...
7224
7225 class A:
7226 @dec
7227 def __init__(self, x: int) -> None: ...
7228
7229 class B:
7230 @dec
7231 def __new__(cls, x: int) -> B: ...
7232
7233 reveal_type(A) # N: Revealed type is "def (x: builtins.int) -> __main__.A"
7234 reveal_type(B) # N: Revealed type is "def (x: builtins.int) -> __main__.B"
7235
7236 [case testDecoratedConstructorsBad]
7237 from typing import Callable, Any
7238
7239 def dec(f: Callable[[Any, int], Any]) -> int: ...
7240
7241 class A:
7242 @dec # E: Unsupported decorated constructor type
7243 def __init__(self, x: int) -> None: ...
7244
7245 class B:
7246 @dec # E: Unsupported decorated constructor type
7247 def __new__(cls, x: int) -> B: ...
7248
7249 [case testIgnorePrivateAttributesTypeCheck]
7250 class B:
7251 __foo_: int
7252 class C(B):
7253 __foo_: str
7254 [out]
7255
7256 [case testIgnorePrivateMethodsTypeCheck]
7257 class B:
7258 def __foo_(self) -> int: ...
7259 class C(B):
7260 def __foo_(self) -> str: ...
7261 [out]
7262
7263 [case testCheckForPrivateMethodsWhenPublicCheck]
7264 class B:
7265 __foo__: int
7266 class C(B):
7267 __foo__: str
7268 [out]
7269 main:4: error: Incompatible types in assignment (expression has type "str", base class "B" defined the type as "int")
7270
7271 [case testIgnorePrivateMethodsTypeCheck2]
7272 class A:
7273 def __foo_(self) -> int: ...
7274 class B:
7275 def __foo_(self) -> str: ...
7276
7277 class C(A, B): pass
7278 [out]
7279
7280 [case testAttributeDefOrder1]
7281 import a
7282
7283 [file a.py]
7284 from b import C
7285
7286 class D(C):
7287 def g(self) -> None:
7288 self.x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
7289
7290 def f(self) -> None:
7291 reveal_type(self.x) # N: Revealed type is "builtins.int"
7292
7293
7294 [file b.py]
7295 import a
7296
7297 class C:
7298 def __init__(self) -> None:
7299 self.x = 0
7300
7301 [targets b, a, b.C.__init__, a.D.g, a.D.f, __main__]
7302
7303 [case testAttributeDefOrder2]
7304 class D(C):
7305 def g(self) -> None:
7306 self.x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
7307
7308 def f(self) -> None:
7309 reveal_type(self.x) # N: Revealed type is "builtins.int"
7310
7311
7312 class C:
7313 def __init__(self) -> None:
7314 self.x = 0
7315
7316 class E(C):
7317 def g(self) -> None:
7318 self.x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
7319
7320 def f(self) -> None:
7321 reveal_type(self.x) # N: Revealed type is "builtins.int"
7322
7323 [targets __main__, __main__, __main__.C.__init__, __main__.D.g, __main__.D.f, __main__.E.g, __main__.E.f]
7324
7325 [case testNewReturnType1]
7326 class A:
7327 def __new__(cls) -> B:
7328 pass
7329
7330 class B(A): pass
7331
7332 reveal_type(A()) # N: Revealed type is "__main__.B"
7333 reveal_type(B()) # N: Revealed type is "__main__.B"
7334
7335 [case testNewReturnType2]
7336 from typing import Any
7337
7338 # make sure that __new__ method that return implicit Any are ignored when
7339 # determining the return type
7340 class A:
7341 def __new__(cls):
7342 pass
7343
7344 class B:
7345 def __new__(cls, x: int = 0) -> Any:
7346 pass
7347
7348 class C:
7349 def __new__(cls, x: int = 0):
7350 pass
7351
7352 reveal_type(A()) # N: Revealed type is "__main__.A"
7353 reveal_type(B()) # N: Revealed type is "Any"
7354 reveal_type(B(1)) # N: Revealed type is "Any"
7355 reveal_type(C()) # N: Revealed type is "__main__.C"
7356 reveal_type(C(1)) # N: Revealed type is "__main__.C"
7357
7358 [case testNewReturnType3]
7359
7360 # Check for invalid __new__ typing
7361
7362 class A:
7363 def __new__(cls) -> int: # E: Incompatible return type for "__new__" (returns "int", but must return a subtype of "A")
7364 pass
7365
7366 reveal_type(A()) # N: Revealed type is "builtins.int"
7367
7368 [case testNewReturnType4]
7369 from typing import TypeVar, Type
7370
7371 # Check for __new__ using type vars
7372
7373 TX = TypeVar('TX', bound='X')
7374 class X:
7375 def __new__(lol: Type[TX], x: int) -> TX:
7376 pass
7377 class Y(X): pass
7378
7379 reveal_type(X(20)) # N: Revealed type is "__main__.X"
7380 reveal_type(Y(20)) # N: Revealed type is "__main__.Y"
7381
7382 [case testNewReturnType5]
7383 from typing import Any, TypeVar, Generic, overload
7384
7385 T = TypeVar('T')
7386 class O(Generic[T]):
7387 @overload
7388 def __new__(cls) -> O[int]:
7389 pass
7390 @overload
7391 def __new__(cls, x: int) -> O[str]:
7392 pass
7393 def __new__(cls, x: int = 0) -> O[Any]:
7394 pass
7395
7396 reveal_type(O()) # N: Revealed type is "__main__.O[builtins.int]"
7397 reveal_type(O(10)) # N: Revealed type is "__main__.O[builtins.str]"
7398
7399 [case testNewReturnType6]
7400 from typing import Tuple, Optional
7401
7402 # Check for some cases that aren't allowed
7403
7404 class X:
7405 def __new__(cls) -> Optional[Y]: # E: "__new__" must return a class instance (got "Y | None")
7406 pass
7407 class Y:
7408 def __new__(cls) -> Optional[int]: # E: "__new__" must return a class instance (got "int | None")
7409 pass
7410
7411
7412 [case testNewReturnType7]
7413 from typing import NamedTuple
7414
7415 # ... test __new__ returning tuple type
7416 class A:
7417 def __new__(cls) -> 'B':
7418 pass
7419
7420 N = NamedTuple('N', [('x', int)])
7421 class B(A, N): pass
7422
7423 reveal_type(A()) # N: Revealed type is "tuple[builtins.int, fallback=__main__.B]"
7424 [builtins fixtures/tuple.pyi]
7425
7426 [case testNewReturnType8]
7427 from typing import TypeVar, Any
7428
7429 # test type var from a different argument
7430 TX = TypeVar('TX', bound='X')
7431 class X:
7432 def __new__(cls, x: TX) -> TX: # E: "__new__" must return a class instance (got "TX")
7433 pass
7434
7435 [case testNewReturnType9]
7436 class A:
7437 def __new__(cls) -> A:
7438 pass
7439
7440 class B(A):
7441 pass
7442
7443 reveal_type(B()) # N: Revealed type is "__main__.B"
7444
7445 [case testNewReturnType10]
7446 # https://github.com/python/mypy/issues/11398
7447 from typing import Type
7448
7449 class MyMetaClass(type):
7450 def __new__(cls, name, bases, attrs) -> Type['MyClass']:
7451 pass
7452
7453 class MyClass(metaclass=MyMetaClass):
7454 pass
7455
7456 [case testNewReturnType11]
7457 # https://github.com/python/mypy/issues/11398
7458 class MyMetaClass(type):
7459 def __new__(cls, name, bases, attrs) -> type:
7460 pass
7461
7462 class MyClass(metaclass=MyMetaClass):
7463 pass
7464
7465 [case testNewReturnType12]
7466 # https://github.com/python/mypy/issues/11398
7467 from typing import Type
7468
7469 class MyMetaClass(type):
7470 def __new__(cls, name, bases, attrs) -> int: # E: Incompatible return type for "__new__" (returns "int", but must return a subtype of "type")
7471 pass
7472
7473 class MyClass(metaclass=MyMetaClass):
7474 pass
7475
7476 [case testNewReturnType13]
7477 from typing import Protocol
7478
7479 class Foo(Protocol):
7480 def foo(self) -> str: ...
7481
7482 class A:
7483 def __new__(cls) -> Foo: ... # E: Incompatible return type for "__new__" (returns "Foo", but must return a subtype of "A")
7484
7485 reveal_type(A()) # N: Revealed type is "__main__.Foo"
7486 reveal_type(A().foo()) # N: Revealed type is "builtins.str"
7487
7488 [case testNewReturnType14]
7489 from __future__ import annotations
7490
7491 class A:
7492 def __new__(cls) -> int: raise # E: Incompatible return type for "__new__" (returns "int", but must return a subtype of "A")
7493
7494 class B(A):
7495 @classmethod
7496 def foo(cls) -> int: raise
7497
7498 reveal_type(B.foo()) # N: Revealed type is "builtins.int"
7499 [builtins fixtures/classmethod.pyi]
7500
7501 [case testNewReturnType15]
7502 from typing import Generic, Type, TypeVar
7503
7504 T = TypeVar("T")
7505
7506 class A(Generic[T]):
7507 def __new__(cls) -> B[int]: ...
7508 @classmethod
7509 def foo(cls: Type[A[T]]) -> T: ...
7510
7511 class B(A[T]): ...
7512
7513 # The Never without error is not ideal, but matches the behavior without custom __new__().
7514 reveal_type(B.foo()) # N: Revealed type is "Never"
7515 reveal_type(B[str].foo()) # N: Revealed type is "builtins.str"
7516
7517 class C(A[str]): ...
7518
7519 reveal_type(C.foo()) # N: Revealed type is "builtins.str"
7520 [builtins fixtures/classmethod.pyi]
7521
7522 [case testNewReturnType16]
7523 from typing import Generic, TypeVar
7524
7525 T = TypeVar("T")
7526 class A(Generic[T]):
7527 def __new__(cls, *args, **kwargs) -> T: # E: "__new__" must return a class instance (got "T")
7528 ...
7529
7530 class Model:
7531 pass
7532
7533 reveal_type(A[Model]()) # N: Revealed type is "__main__.Model"
7534
7535 class B(A[Model]):
7536 pass
7537
7538 reveal_type(B()) # N: Revealed type is "__main__.Model"
7539 [builtins fixtures/dict.pyi]
7540
7541 [case testNewReturnType17]
7542 class C:
7543 def __new__(self) -> D:
7544 return D()
7545
7546 class D(C):
7547 x: int
7548
7549 C.x # E: "type[C]" has no attribute "x"
7550
7551 [case testNewReturnType18]
7552 class A:
7553 def __new__(cls) -> A:
7554 return A()
7555
7556 class B(A):
7557 def __new__(cls) -> A: # E: Incompatible return type for "__new__" (returns "A", but must return a subtype of "B")
7558 return super().__new__(cls)
7559
7560 class C(B): ...
7561
7562 # Always respect explicit return type after giving an error.
7563 reveal_type(B()) # N: Revealed type is "__main__.A"
7564 reveal_type(C()) # N: Revealed type is "__main__.A"
7565
7566 # Ignore "implicit" return type to preserve backwards compatibility.
7567 class D(A): ...
7568 reveal_type(D()) # N: Revealed type is "__main__.D"
7569
7570 [case testNewReturnType19]
7571 from typing import TypeVar
7572
7573 T = TypeVar("T")
7574
7575 def f(tp: type[T]) -> T: ...
7576
7577 class C:
7578 def __new__(cls) -> int: ... # type: ignore[misc]
7579
7580 reveal_type(f(C)) # N: Revealed type is "__main__.C"
7581
7582 [case testNewReturnTypeCallableSubtyping]
7583 from typing import Callable, Protocol
7584
7585 class Foo:
7586 def foo(self) -> None: ...
7587
7588 class A:
7589 def __new__(cls) -> Foo: ... # type: ignore
7590
7591 ta: type[A]
7592 tf: type[Foo]
7593
7594 class PA(Protocol):
7595 def __call__(self) -> A: ...
7596
7597 class PFoo(Protocol):
7598 def __call__(self) -> Foo: ...
7599
7600 def f(x: Callable[[], A]) -> None: ...
7601 def g(x: Callable[[], Foo]) -> None: ...
7602 def fp(x: PA) -> None: ...
7603 def gp(x: PFoo) -> None: ...
7604 def h(x: type[A]) -> None: ...
7605 def i(x: type[Foo]) -> None: ...
7606
7607 f(A) # E: Argument 1 to "f" has incompatible type "type[A]"; expected "Callable[[], A]"
7608 g(A)
7609 fp(A) # E: Argument 1 to "fp" has incompatible type "type[A]"; expected "PA" \
7610 # N: "A" has constructor incompatible with "__call__" of "PA" \
7611 # N: Following member(s) of "A" have conflicts: \
7612 # N: Expected: \
7613 # N: def __call__() -> A \
7614 # N: Got: \
7615 # N: def A() -> Foo \
7616 # N: "PA.__call__" has type "Callable[[], A]"
7617 gp(A)
7618 h(A)
7619 i(A) # E: Argument 1 to "i" has incompatible type "type[A]"; expected "type[Foo]"
7620
7621 f(Foo) # E: Argument 1 to "f" has incompatible type "type[Foo]"; expected "Callable[[], A]"
7622 g(Foo)
7623 fp(Foo) # E: Argument 1 to "fp" has incompatible type "type[Foo]"; expected "PA" \
7624 # N: "Foo" has constructor incompatible with "__call__" of "PA" \
7625 # N: Following member(s) of "Foo" have conflicts: \
7626 # N: Expected: \
7627 # N: def __call__() -> A \
7628 # N: Got: \
7629 # N: def Foo() -> Foo \
7630 # N: "PA.__call__" has type "Callable[[], A]"
7631 gp(Foo)
7632 h(Foo) # E: Argument 1 to "h" has incompatible type "type[Foo]"; expected "type[A]"
7633 i(Foo)
7634
7635 f(ta) # E: Argument 1 to "f" has incompatible type "type[A]"; expected "Callable[[], A]"
7636 g(ta)
7637 fp(ta) # E: Argument 1 to "fp" has incompatible type "type[A]"; expected "PA" \
7638 # N: "A" has constructor incompatible with "__call__" of "PA" \
7639 # N: Following member(s) of "A" have conflicts: \
7640 # N: Expected: \
7641 # N: def __call__() -> A \
7642 # N: Got: \
7643 # N: def A() -> Foo \
7644 # N: "PA.__call__" has type "Callable[[], A]"
7645 gp(ta)
7646 h(ta)
7647 i(ta) # E: Argument 1 to "i" has incompatible type "type[A]"; expected "type[Foo]"
7648
7649 f(tf) # E: Argument 1 to "f" has incompatible type "type[Foo]"; expected "Callable[[], A]"
7650 g(tf)
7651 fp(tf) # E: Argument 1 to "fp" has incompatible type "type[Foo]"; expected "PA" \
7652 # N: "Foo" has constructor incompatible with "__call__" of "PA" \
7653 # N: Following member(s) of "Foo" have conflicts: \
7654 # N: Expected: \
7655 # N: def __call__() -> A \
7656 # N: Got: \
7657 # N: def Foo() -> Foo \
7658 # N: "PA.__call__" has type "Callable[[], A]"
7659 gp(tf)
7660 h(tf) # E: Argument 1 to "h" has incompatible type "type[Foo]"; expected "type[A]"
7661 i(tf)
7662
7663 [case testNewReturnTypeCallableJoins]
7664 from typing import TypeVar
7665
7666 class Base: ...
7667 class Foo(Base): ...
7668 class Bar(Base): ...
7669
7670 class Base2: ...
7671
7672 class A(Base2):
7673 def __new__(cls) -> Foo: ... # type: ignore
7674
7675 class B(Base2):
7676 def __new__(cls) -> Bar: ... # type: ignore
7677
7678 T = TypeVar("T")
7679 def join(x: T, y: T) -> T: ...
7680
7681 reveal_type(join(A, Foo)) # N: Revealed type is "def () -> __main__.Foo"
7682 reveal_type(join(Foo, A)) # N: Revealed type is "def () -> __main__.Foo"
7683 reveal_type(join(A, B)) # N: Revealed type is "def () -> __main__.Base"
7684 reveal_type(join(B, A)) # N: Revealed type is "def () -> __main__.Base"
7685
7686 # This tests the type repr in error messages.
7687 j = join(A, B)
7688 x: int = j # E: Incompatible types in assignment (expression has type "type[Base2]", variable has type "int")
7689
7690 [case testNewReturnTypeCallableInference]
7691 from typing import Callable, TypeVar
7692
7693 class A:
7694 def __new__(cls) -> int: ... # type: ignore
7695
7696 T = TypeVar("T")
7697 def foo(f: Callable[[], T]) -> T: ...
7698 def bar(t: type[T]) -> T: ...
7699
7700 ta: type[A]
7701 reveal_type(foo(A)) # N: Revealed type is "builtins.int"
7702 reveal_type(foo(ta)) # N: Revealed type is "builtins.int"
7703 reveal_type(bar(A)) # N: Revealed type is "__main__.A"
7704 reveal_type(bar(ta)) # N: Revealed type is "__main__.A"
7705
7706 [case testNewReturnTypeCallableNarrowing]
7707 from typing import Callable, TypeVar
7708
7709 class A: ...
7710
7711 class B(A):
7712 more = 1
7713 def __new__(cls) -> A: ... # type: ignore
7714
7715 x: A
7716 if isinstance(x, B):
7717 reveal_type(x) # N: Revealed type is "__main__.B"
7718
7719 tx: type[A]
7720 if issubclass(tx, B):
7721 reveal_type(tx) # N: Revealed type is "type[__main__.B]"
7722 [builtins fixtures/isinstancelist.pyi]
7723
7724 [case testNewReturnTypeOverloadNarrowing]
7725 from typing import TypeVar, Generic, Union, overload
7726
7727 T = TypeVar("T", int, str)
7728
7729 class Series(Generic[T]):
7730 @overload
7731 def __new__(cls, dtype: int) -> IntSeries: ...
7732 @overload
7733 def __new__(cls, dtype: type[T]) -> Series[T]: ...
7734 @overload
7735 def __new__(cls, dtype=...) -> Series: ...
7736 def __new__(cls, dtype=...) -> Series:
7737 ...
7738
7739 class IntSeries(Series[int]): ...
7740
7741 class Index:
7742 @overload
7743 def __new__(cls, dtype: int) -> IntIndex: ...
7744 @overload
7745 def __new__(cls, dtype=...) -> Index: ...
7746 def __new__(cls, dtype=...) -> Index:
7747 ...
7748
7749 class IntIndex(Index): ...
7750
7751 def foo(x: Union[Series, int, Index]):
7752 if isinstance(x, (Series, Index)):
7753 reveal_type(x) # N: Revealed type is "__main__.Series[Any] | __main__.Index"
7754 else:
7755 reveal_type(x) # N: Revealed type is "builtins.int"
7756 [builtins fixtures/isinstancelist.pyi]
7757
7758 [case testMetaclassPlaceholderNode]
7759 from sympy.assumptions import ManagedProperties
7760 from sympy.ops import AssocOp
7761 reveal_type(AssocOp.x) # N: Revealed type is "sympy.basic.Basic"
7762 reveal_type(AssocOp.y) # N: Revealed type is "builtins.int"
7763
7764 [file sympy/__init__.py]
7765
7766 [file sympy/assumptions.py]
7767 from .basic import Basic
7768 class ManagedProperties(type):
7769 x: Basic
7770 y: int
7771 # The problem is with the next line,
7772 # it creates the following order (classname, metaclass):
7773 # 1. Basic NameExpr(ManagedProperties)
7774 # 2. AssocOp None
7775 # 3. ManagedProperties None
7776 # 4. Basic NameExpr(ManagedProperties [sympy.assumptions.ManagedProperties])
7777 # So, `AssocOp` will still have `metaclass_type` as `None`
7778 # and all its `mro` types will have `declared_metaclass` as `None`.
7779 from sympy.ops import AssocOp
7780
7781 [file sympy/basic.py]
7782 from .assumptions import ManagedProperties
7783 class Basic(metaclass=ManagedProperties): ...
7784
7785 [file sympy/ops.py]
7786 from sympy.basic import Basic
7787 class AssocOp(Basic): ...
7788
7789 [case testMetaclassSubclassSelf]
7790 # This does not make much sense, but we must not crash:
7791 import a
7792 [file m.py]
7793 from a import A # E: Module "a" has no attribute "A"
7794 class Meta(A): pass
7795 [file a.py]
7796 from m import Meta
7797 class A(metaclass=Meta): pass
7798
7799 [case testMetaclassConflict]
7800 class MyMeta1(type): ...
7801 class MyMeta2(type): ...
7802 class MyMeta3(type): ...
7803 class A(metaclass=MyMeta1): ...
7804 class B(metaclass=MyMeta2): ...
7805 class C(metaclass=type): ...
7806 class A1(A): ...
7807 class E: ...
7808
7809 class CorrectMeta(MyMeta1, MyMeta2): ...
7810 class CorrectSubclass1(A1, B, E, metaclass=CorrectMeta): ...
7811 class CorrectSubclass2(A, B, E, metaclass=CorrectMeta): ...
7812 class CorrectSubclass3(B, A, metaclass=CorrectMeta): ...
7813
7814 class ChildOfCorrectSubclass1(CorrectSubclass1): ...
7815
7816 class CorrectWithType1(C, A1): ...
7817 class CorrectWithType2(B, C): ...
7818
7819 class Conflict1(A1, B, E): ... # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \
7820 # N: "__main__.MyMeta1" (metaclass of "__main__.A") conflicts with "__main__.MyMeta2" (metaclass of "__main__.B")
7821 class Conflict2(A, B): ... # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \
7822 # N: "__main__.MyMeta1" (metaclass of "__main__.A") conflicts with "__main__.MyMeta2" (metaclass of "__main__.B")
7823 class Conflict3(B, A): ... # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \
7824 # N: "__main__.MyMeta2" (metaclass of "__main__.B") conflicts with "__main__.MyMeta1" (metaclass of "__main__.A")
7825
7826 class ChildOfConflict1(Conflict3): ...
7827 class ChildOfConflict2(Conflict3, metaclass=CorrectMeta): ...
7828
7829 class ConflictingMeta(MyMeta1, MyMeta3): ...
7830 class Conflict4(A1, B, E, metaclass=ConflictingMeta): ... # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \
7831 # N: "__main__.ConflictingMeta" (metaclass of "__main__.Conflict4") conflicts with "__main__.MyMeta2" (metaclass of "__main__.B")
7832
7833 class ChildOfCorrectButWrongMeta(CorrectSubclass1, metaclass=ConflictingMeta): # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \
7834 # N: "__main__.ConflictingMeta" (metaclass of "__main__.ChildOfCorrectButWrongMeta") conflicts with "__main__.CorrectMeta" (metaclass of "__main__.CorrectSubclass1")
7835 ...
7836
7837 [case testMetaClassConflictIssue14033]
7838 class M1(type): pass
7839 class M2(type): pass
7840 class Mx(M1, M2): pass
7841
7842 class A1(metaclass=M1): pass
7843 class A2(A1): pass
7844
7845 class B1(metaclass=M2): pass
7846
7847 class C1(metaclass=Mx): pass
7848
7849 class TestABC(A2, B1, C1): pass # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \
7850 # N: "__main__.M1" (metaclass of "__main__.A1") conflicts with "__main__.M2" (metaclass of "__main__.B1")
7851 class TestBAC(B1, A2, C1): pass # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \
7852 # N: "__main__.M2" (metaclass of "__main__.B1") conflicts with "__main__.M1" (metaclass of "__main__.A1")
7853
7854 # should not warn again for children
7855 class ChildOfTestABC(TestABC): pass
7856
7857 # no metaclass is assumed if super class has a metaclass conflict
7858 class ChildOfTestABCMetaMx(TestABC, metaclass=Mx): pass
7859 class ChildOfTestABCMetaM1(TestABC, metaclass=M1): pass
7860
7861 class TestABCMx(A2, B1, C1, metaclass=Mx): pass
7862 class TestBACMx(B1, A2, C1, metaclass=Mx): pass
7863
7864 class TestACB(A2, C1, B1): pass
7865 class TestBCA(B1, C1, A2): pass
7866
7867 class TestCAB(C1, A2, B1): pass
7868 class TestCBA(C1, B1, A2): pass
7869
7870 [case testGenericOverride]
7871 from typing import Generic, TypeVar, Any
7872
7873 T = TypeVar('T')
7874
7875 class B(Generic[T]):
7876 x: T
7877
7878 class C(B):
7879 def __init__(self) -> None:
7880 self.x: Any
7881
7882 [case testGenericOverridePreciseInvalid]
7883 from typing import Generic, TypeVar, Any
7884
7885 T = TypeVar('T')
7886
7887 class B(Generic[T]):
7888 x: T
7889
7890 class C(B[str]):
7891 def __init__(self) -> None:
7892 self.x: int # E: Incompatible types in assignment (expression has type "int", base class "B" defined the type as "str")
7893
7894 [case testGenericOverridePreciseValid]
7895 from typing import Generic, TypeVar
7896
7897 T = TypeVar('T')
7898
7899 class B(Generic[T]):
7900 x: T
7901
7902 class C(B[float]):
7903 def __init__(self) -> None:
7904 self.x: int # We currently allow covariant overriding.
7905
7906 [case testGenericOverrideGeneric]
7907 from typing import Generic, TypeVar, List
7908
7909 T = TypeVar('T')
7910
7911 class B(Generic[T]):
7912 x: T
7913
7914 class C(B[T]):
7915 def __init__(self) -> None:
7916 self.x: List[T] # E: Incompatible types in assignment (expression has type "list[T]", base class "B" defined the type as "T")
7917 [builtins fixtures/list.pyi]
7918
7919 [case testGenericOverrideGenericChained]
7920 from typing import Generic, TypeVar, Tuple
7921
7922 T = TypeVar('T')
7923 S = TypeVar('S')
7924
7925 class A(Generic[T]):
7926 x: T
7927
7928 class B(A[Tuple[T, S]]): ...
7929
7930 class C(B[int, T]):
7931 def __init__(self) -> None:
7932 # TODO: error message could be better.
7933 self.x: Tuple[str, T] # E: Incompatible types in assignment (expression has type "tuple[str, T]", base class "A" defined the type as "tuple[int, T]")
7934 [builtins fixtures/tuple.pyi]
7935
7936 [case testInitSubclassWrongType]
7937 class Base:
7938 default_name: str
7939
7940 def __init_subclass__(cls, default_name: str):
7941 super().__init_subclass__()
7942 cls.default_name = default_name
7943 return
7944
7945 class Child(Base, default_name=5): # E: Argument "default_name" to "__init_subclass__" of "Base" has incompatible type "int"; expected "str"
7946 pass
7947 [builtins fixtures/object_with_init_subclass.pyi]
7948
7949 [case testInitSubclassTooFewArgs]
7950 class Base:
7951 default_name: str
7952
7953 def __init_subclass__(cls, default_name: str, **kwargs):
7954 super().__init_subclass__()
7955 cls.default_name = default_name
7956 return
7957
7958 class Child(Base): # E: Missing positional argument "default_name" in call to "__init_subclass__" of "Base"
7959 pass
7960 [builtins fixtures/object_with_init_subclass.pyi]
7961
7962 [case testInitSubclassTooFewArgs2]
7963 class Base:
7964 default_name: str
7965
7966 def __init_subclass__(cls, default_name: str, thing: int):
7967 super().__init_subclass__()
7968 cls.default_name = default_name
7969 return
7970 # TODO implement this, so that no error is raised?
7971 d = {"default_name": "abc", "thing": 0}
7972 class Child(Base, **d): # E: Missing positional arguments "default_name", "thing" in call to "__init_subclass__" of "Base"
7973 pass
7974 [builtins fixtures/object_with_init_subclass.pyi]
7975
7976 [case testInitSubclassOK]
7977 class Base:
7978 default_name: str
7979 thing: int
7980
7981 def __init_subclass__(cls, default_name: str, thing:int, **kwargs):
7982 super().__init_subclass__()
7983 cls.default_name = default_name
7984 return
7985
7986 class Child(Base, thing=5, default_name=""):
7987 pass
7988 [builtins fixtures/object_with_init_subclass.pyi]
7989
7990 [case testInitSubclassWithMetaclassOK]
7991 class Base:
7992 thing: int
7993
7994 def __init_subclass__(cls, thing: int):
7995 cls.thing = thing
7996
7997 class Child(Base, metaclass=type, thing=0):
7998 pass
7999 [builtins fixtures/object_with_init_subclass.pyi]
8000
8001 [case testInitSubclassWithCustomMetaclassOK]
8002 class M(type): ...
8003 class Child(metaclass=M, thing=0):
8004 pass
8005 [builtins fixtures/object_with_init_subclass.pyi]
8006
8007 [case testTooManyArgsForObject]
8008 class A(thing=5):
8009 pass
8010 [out]
8011 main:1: error: Unexpected keyword argument "thing" for "__init_subclass__" of "object"
8012 [builtins fixtures/object_with_init_subclass.pyi]
8013
8014 [case testInitSubclassWithImports]
8015 from init_subclass.a import Base
8016 class Child(Base, thing=5): # E: Missing positional argument "default_name" in call to "__init_subclass__" of "Base"
8017 pass
8018 [file init_subclass/a.py]
8019 class Base:
8020 default_name: str
8021 thing: int
8022
8023 def __init_subclass__(cls, default_name: str, thing:int, **kwargs):
8024 pass
8025 [file init_subclass/__init__.py]
8026 [builtins fixtures/object_with_init_subclass.pyi]
8027
8028 [case testInitSubclassWithImportsOK]
8029 from init_subclass.a import MidBase
8030 class Main(MidBase, test=True): pass
8031 [file init_subclass/a.py]
8032 class Base:
8033 def __init_subclass__(cls, **kwargs) -> None: pass
8034 class MidBase(Base): pass
8035 [file init_subclass/__init__.py]
8036 [builtins fixtures/object_with_init_subclass.pyi]
8037
8038 [case testInitSubclassUnannotated]
8039 class A:
8040 def __init_subclass__(cls, *args, **kwargs):
8041 super().__init_subclass__(*args, **kwargs)
8042
8043 class B(A):
8044 pass
8045
8046 reveal_type(A.__init_subclass__) # N: Revealed type is "def (*args: Any, **kwargs: Any) -> Any"
8047 [builtins fixtures/object_with_init_subclass.pyi]
8048
8049 [case testInitSubclassUnannotatedMulti]
8050 from typing import ClassVar, List, Type
8051
8052 class A:
8053 registered_classes: ClassVar[List[Type[A]]] = []
8054 def __init_subclass__(cls, *args, register=True, **kwargs):
8055 if register:
8056 cls.registered_classes.append(cls)
8057 super().__init_subclass__(*args, **kwargs)
8058
8059 class B(A): ...
8060 class C(A, register=False): ...
8061 class D(C): ...
8062 [builtins fixtures/object_with_init_subclass.pyi]
8063
8064 [case testClassMethodUnannotated]
8065 class C:
8066 def __new__(cls): ...
8067 @classmethod
8068 def meth(cls): ...
8069
8070 reveal_type(C.meth) # N: Revealed type is "def () -> Any"
8071 reveal_type(C.__new__) # N: Revealed type is "def (cls: type[__main__.C]) -> Any"
8072 [builtins fixtures/classmethod.pyi]
8073
8074 [case testOverrideGenericSelfClassMethod]
8075 from typing import Generic, TypeVar, Type, List
8076
8077 T = TypeVar('T', bound='A')
8078
8079 class A:
8080 @classmethod
8081 def meth(cls: Type[T]) -> List[T]: ...
8082
8083 class B(A):
8084 @classmethod
8085 def meth(cls: Type[T]) -> List[T]: ...
8086
8087 [builtins fixtures/isinstancelist.pyi]
8088
8089 [case testCheckUntypedDefsSelf1]
8090 # flags: --check-untyped-defs
8091
8092 from typing import Generic, TypeVar
8093 T = TypeVar('T')
8094
8095 class Desc:
8096 def __get__(self, x, y):
8097 # type: (...) -> bool
8098 pass
8099
8100 class Foo:
8101 y = Desc()
8102
8103 def __init__(self):
8104 self.x = 0
8105
8106 def foo(self):
8107 reveal_type(self.x) # N: Revealed type is "builtins.int"
8108 reveal_type(self.y) # N: Revealed type is "builtins.bool"
8109 self.bar()
8110 self.baz() # E: "Foo" has no attribute "baz"
8111
8112 @classmethod
8113 def bar(cls):
8114 cls.baz() # E: "type[Foo]" has no attribute "baz"
8115
8116 class C(Generic[T]):
8117 x: T
8118 def meth(self):
8119 self.x + 1 # E: Unsupported left operand type for + ("T")
8120 [builtins fixtures/classmethod.pyi]
8121
8122 [case testCheckUntypedDefsSelf2]
8123 # flags: --check-untyped-defs
8124
8125 class Foo:
8126 def __init__(self):
8127 self.x = None
8128 self.y = []
8129
8130 reveal_type(Foo().x) # N: Revealed type is "Any | None"
8131 reveal_type(Foo().y) # N: Revealed type is "builtins.list[Any]"
8132 [builtins fixtures/list.pyi]
8133
8134 [case testCheckUntypedDefsSelf3]
8135 # flags: --check-untyped-defs
8136
8137 class Foo:
8138 def bad(): # E: Method must have at least one argument. Did you forget the "self" argument?
8139 self.x = 0 # E: Name "self" is not defined
8140
8141 [case testMethodSelfArgumentChecks]
8142 from typing import Callable, ParamSpec, TypeVar
8143
8144 T = TypeVar("T")
8145 P = ParamSpec("P")
8146
8147 def to_number_1(fn: Callable[[], int]) -> int:
8148 return 0
8149
8150 def to_number_2(fn: Callable[[int], int]) -> int:
8151 return 0
8152
8153 def to_same_callable(fn: Callable[P, T]) -> Callable[P, T]:
8154 return fn
8155
8156 class A:
8157 def undecorated() -> None: ... # E: Method must have at least one argument. Did you forget the "self" argument?
8158
8159 def undecorated_not_self(x: int) -> None: ... # E: "self" parameter missing for a non-static method (or an invalid type for self)
8160
8161 def undecorated_not_self_2(self: int) -> None: ... # E: The erased type of self "builtins.int" is not a supertype of its class "__main__.A"
8162
8163 @to_number_1
8164 def fn1() -> int:
8165 return 0
8166
8167 @to_number_1 # E: Argument 1 to "to_number_1" has incompatible type "Callable[[int], int]"; expected "Callable[[], int]"
8168 def fn2(_x: int) -> int:
8169 return 0
8170
8171 @to_number_2 # E: Argument 1 to "to_number_2" has incompatible type "Callable[[], int]"; expected "Callable[[int], int]"
8172 def fn3() -> int:
8173 return 0
8174
8175 @to_number_2
8176 def fn4(_x: int) -> int:
8177 return 0
8178
8179 @to_number_2 # E: Argument 1 to "to_number_2" has incompatible type "Callable[[str], int]"; expected "Callable[[int], int]"
8180 def fn5(_x: str) -> int:
8181 return 0
8182
8183 @to_same_callable
8184 def g1() -> None: ... # E: Method must have at least one argument. Did you forget the "self" argument?
8185
8186 @to_same_callable
8187 def g2(x: int) -> None: ... # E: "self" parameter missing for a non-static method (or an invalid type for self)
8188
8189 @to_same_callable
8190 def g3(self: int) -> None: ... # E: The erased type of self "builtins.int" is not a supertype of its class "__main__.A"
8191
8192 reveal_type(A().fn1) # N: Revealed type is "builtins.int"
8193 reveal_type(A().fn2) # N: Revealed type is "builtins.int"
8194 reveal_type(A().fn3) # N: Revealed type is "builtins.int"
8195 reveal_type(A().fn4) # N: Revealed type is "builtins.int"
8196 reveal_type(A().fn5) # N: Revealed type is "builtins.int"
8197
8198 reveal_type(A().g1) # E: Attribute function "g1" with type "Callable[[], None]" does not accept self argument \
8199 # N: Revealed type is "def ()"
8200 reveal_type(A().g2) # E: Invalid self argument "A" to attribute function "g2" with type "Callable[[int], None]" \
8201 # N: Revealed type is "def ()"
8202 reveal_type(A().g3) # E: Invalid self argument "A" to attribute function "g3" with type "Callable[[int], None]" \
8203 # N: Revealed type is "def ()"
8204 [builtins fixtures/tuple.pyi]
8205
8206 [case testMethodSelfArgumentChecksConcatenate]
8207 from typing import Callable, ParamSpec, TypeVar
8208 from typing_extensions import Concatenate
8209
8210 T = TypeVar("T")
8211 P = ParamSpec("P")
8212 R = TypeVar("R")
8213
8214 def to_same_callable(fn: Callable[Concatenate[T, P], R]) -> Callable[Concatenate[T, P], R]:
8215 return fn
8216
8217 def remove_first(fn: Callable[Concatenate[T, P], R]) -> Callable[P, R]:
8218 ...
8219
8220 def add_correct_first(fn: Callable[P, R]) -> Callable[Concatenate["C", P], R]:
8221 ...
8222
8223 def add_wrong_first(fn: Callable[P, R]) -> Callable[Concatenate[int, P], R]:
8224 ...
8225
8226 class A:
8227 @to_same_callable # E: Argument 1 to "to_same_callable" has incompatible type "Callable[[], int]"; expected "Callable[[T], int]"
8228 def fn1() -> int:
8229 return 0
8230
8231 @to_same_callable
8232 def fn2(_x: int) -> int: # E: "self" parameter missing for a non-static method (or an invalid type for self)
8233 return 0
8234
8235 @to_same_callable
8236 def fn3(self, _x: int) -> int:
8237 return 0
8238
8239 reveal_type(A().fn1) # N: Revealed type is "def () -> builtins.int"
8240 reveal_type(A().fn2) # E: Invalid self argument "A" to attribute function "fn2" with type "Callable[[int], int]" \
8241 # N: Revealed type is "def () -> builtins.int"
8242 reveal_type(A().fn3) # N: Revealed type is "def (_x: builtins.int) -> builtins.int"
8243
8244 class B:
8245 @remove_first # E: Argument 1 to "remove_first" has incompatible type "Callable[[], int]"; expected "Callable[[T], int]"
8246 def fn1() -> int: # E: Method must have at least one argument. Did you forget the "self" argument?
8247 return 0
8248
8249 @remove_first
8250 def fn2(_x: int) -> int: # E: Method must have at least one argument. Did you forget the "self" argument?
8251 return 0
8252
8253 @remove_first
8254 def fn3(self, _x: int) -> int: # E: "self" parameter missing for a non-static method (or an invalid type for self)
8255 return 0
8256
8257 @remove_first
8258 def fn4(self, new_self: 'B') -> int:
8259 return 0
8260
8261 reveal_type(B().fn1) # E: Attribute function "fn1" with type "Callable[[], int]" does not accept self argument \
8262 # N: Revealed type is "def () -> builtins.int"
8263 reveal_type(B().fn2) # E: Attribute function "fn2" with type "Callable[[], int]" does not accept self argument \
8264 # N: Revealed type is "def () -> builtins.int"
8265 reveal_type(B().fn3) # E: Invalid self argument "B" to attribute function "fn3" with type "Callable[[int], int]" \
8266 # N: Revealed type is "def () -> builtins.int"
8267 reveal_type(B().fn4) # N: Revealed type is "def () -> builtins.int"
8268
8269 class C:
8270 @add_correct_first
8271 def fn1() -> int:
8272 return 0
8273
8274 @add_correct_first
8275 def fn2(_x: int) -> int:
8276 return 0
8277
8278 @add_correct_first
8279 def fn3(self, _x: int) -> int:
8280 return 0
8281
8282 reveal_type(C().fn1) # N: Revealed type is "def () -> builtins.int"
8283 reveal_type(C().fn2) # N: Revealed type is "def (_x: builtins.int) -> builtins.int"
8284 reveal_type(C().fn3) # N: Revealed type is "def (self: __main__.C, _x: builtins.int) -> builtins.int"
8285
8286 class D:
8287 @add_wrong_first
8288 def fn1() -> int: # E: "self" parameter missing for a non-static method (or an invalid type for self)
8289 return 0
8290
8291 @add_wrong_first
8292 def fn2(_x: int) -> int: # E: "self" parameter missing for a non-static method (or an invalid type for self)
8293 return 0
8294
8295 @add_wrong_first
8296 def fn3(self, _x: int) -> int: # E: "self" parameter missing for a non-static method (or an invalid type for self)
8297 return 0
8298
8299 reveal_type(D().fn1) # E: Invalid self argument "D" to attribute function "fn1" with type "Callable[[int], int]" \
8300 # N: Revealed type is "def () -> builtins.int"
8301 reveal_type(D().fn2) # E: Invalid self argument "D" to attribute function "fn2" with type "Callable[[int, int], int]" \
8302 # N: Revealed type is "def (_x: builtins.int) -> builtins.int"
8303 reveal_type(D().fn3) # E: Invalid self argument "D" to attribute function "fn3" with type "Callable[[int, D, int], int]" \
8304 # N: Revealed type is "def (self: __main__.D, _x: builtins.int) -> builtins.int"
8305 [builtins fixtures/tuple.pyi]
8306
8307 [case testMethodSelfArgumentChecksInUntyped]
8308 from typing import Callable, ParamSpec, TypeVar
8309
8310 T = TypeVar("T")
8311 P = ParamSpec("P")
8312
8313 def to_same_callable(fn: Callable[P, T]) -> Callable[P, T]:
8314 return fn
8315
8316 def unchecked():
8317 class Bad:
8318 def fn() -> None: ... # E: Method must have at least one argument. Did you forget the "self" argument?
8319 def fn2(x: int) -> None: ... # E: "self" parameter missing for a non-static method (or an invalid type for self)
8320
8321 # TODO: would be nice to make this error, but now we see the func
8322 # being decorated as Any, not as a callable
8323 @to_same_callable
8324 def gaaa() -> None: ...
8325 @to_same_callable
8326 def gaaa2(x: int) -> None: ...
8327
8328 class Ok:
8329 def fn(): ...
8330 def fn2(x): ...
8331
8332 @to_same_callable
8333 def g(): ...
8334 @to_same_callable
8335 def g2(x): ...
8336
8337 def checked() -> None:
8338 class Bad:
8339 def fn() -> None: ... # E: Method must have at least one argument. Did you forget the "self" argument?
8340 def fn2(x: int) -> None: ... # E: "self" parameter missing for a non-static method (or an invalid type for self)
8341
8342 @to_same_callable
8343 def g() -> None: ... # E: Method must have at least one argument. Did you forget the "self" argument?
8344 @to_same_callable
8345 def g2(x: int) -> None: ... # E: "self" parameter missing for a non-static method (or an invalid type for self)
8346
8347 class AlsoBad:
8348 def fn(): ... # E: Method must have at least one argument. Did you forget the "self" argument?
8349 def fn2(x): ...
8350
8351 @to_same_callable
8352 def g(): ... # E: Method must have at least one argument. Did you forget the "self" argument?
8353 @to_same_callable
8354 def g2(x): ...
8355
8356 class Ok:
8357 def fn(): ... # E: Method must have at least one argument. Did you forget the "self" argument?
8358 def fn2(x): ...
8359
8360 @to_same_callable
8361 def g(): ... # E: Method must have at least one argument. Did you forget the "self" argument?
8362 @to_same_callable
8363 def g2(x): ...
8364 [builtins fixtures/tuple.pyi]
8365
8366 [case testTypeAfterAttributeAccessWithDisallowAnyExpr]
8367 # flags: --disallow-any-expr
8368
8369 def access_before_declaration(self) -> None:
8370 obj = Foo('bar')
8371 obj.value
8372 x = 1
8373
8374 reveal_type(x) # N: Revealed type is "builtins.int"
8375 x = x + 1
8376
8377 class Foo:
8378 def __init__(self, value: str) -> None:
8379 self.value = value
8380
8381 def access_after_declaration(self) -> None:
8382 obj = Foo('bar')
8383 obj.value
8384 x = 1
8385
8386 reveal_type(x) # N: Revealed type is "builtins.int"
8387 x = x + 1
8388
8389 [case testIsSubClassNarrowDownTypesOfTypeVariables]
8390 from typing import Type, TypeVar, Generic
8391
8392 class Base:
8393 field: int = 42
8394
8395 TypeT = TypeVar("TypeT", bound=type)
8396
8397 TypeT1 = TypeVar("TypeT1", bound=Type[Base])
8398
8399 class C1:
8400 def method(self, other: type) -> int:
8401 if issubclass(other, Base):
8402 reveal_type(other) # N: Revealed type is "type[__main__.Base]"
8403 return other.field
8404 return 0
8405
8406 class C2(Generic[TypeT]):
8407 def method(self, other: TypeT) -> int:
8408 if issubclass(other, Base):
8409 reveal_type(other) # N: Revealed type is "TypeT`1"
8410 return other.field
8411 return 0
8412
8413 class C3(Generic[TypeT1]):
8414 def method(self, other: TypeT1) -> int:
8415 if issubclass(other, Base):
8416 reveal_type(other) # N: Revealed type is "TypeT1`1"
8417 return other.field
8418 return 0
8419
8420 [builtins fixtures/isinstancelist.pyi]
8421
8422 [case testPropertyWithExtraMethod]
8423 def dec(f):
8424 return f
8425
8426 class A:
8427 @property
8428 def x(self): ...
8429 @x.setter
8430 def x(self, value) -> None: ...
8431 def x(self) -> None: ... # E: Unexpected definition for property "x"
8432
8433 @property
8434 def y(self) -> int: ...
8435 @y.setter
8436 def y(self, value: int) -> None: ...
8437 @dec # E: Only supported top decorators are "@y.setter" and "@y.deleter"
8438 def y(self) -> None: ...
8439
8440 reveal_type(A().y) # N: Revealed type is "builtins.int"
8441 [builtins fixtures/property.pyi]
8442
8443 [case testEnclosingScopeLambdaNoCrash]
8444 class C:
8445 x = lambda x: x.y.g()
8446
8447 [case testEnclosingScopeLambdaNoCrashExplicit]
8448 from typing import Callable
8449 class C:
8450 x: Callable[[C], int] = lambda x: x.y.g() # E: "C" has no attribute "y"
8451
8452 [case testOpWithInheritedFromAny-xfail]
8453 from typing import Any
8454 C: Any
8455 class D(C):
8456 pass
8457
8458 class D1(C):
8459 def __add__(self, rhs: float) -> D1:
8460 return self
8461
8462 reveal_type(0.5 + C) # N: Revealed type is "Any"
8463
8464 reveal_type(0.5 + D()) # N: Revealed type is "Any"
8465 reveal_type(D() + 0.5) # N: Revealed type is "Any"
8466 reveal_type("str" + D()) # N: Revealed type is "builtins.str"
8467 reveal_type(D() + "str") # N: Revealed type is "Any"
8468
8469
8470 reveal_type(0.5 + D1()) # N: Revealed type is "Any"
8471 reveal_type(D1() + 0.5) # N: Revealed type is "__main__.D1"
8472 [builtins fixtures/primitives.pyi]
8473
8474 [case testRefMethodWithDecorator]
8475 from typing import Type, final
8476
8477 class A:
8478 pass
8479
8480 class B:
8481 @staticmethod
8482 def A() -> Type[A]: ...
8483 @staticmethod
8484 def B() -> Type[A]: # E: Function "__main__.B.A" is not valid as a type \
8485 # N: Perhaps you need "Callable[...]" or a callback protocol?
8486 return A
8487
8488 class C:
8489 @final
8490 @staticmethod
8491 def A() -> Type[A]:
8492 return A
8493
8494 [builtins fixtures/staticmethod.pyi]
8495
8496 [case testRefMethodWithOverloadDecorator]
8497 from typing import Type, overload
8498
8499 class A:
8500 pass
8501
8502 class B:
8503 @classmethod
8504 @overload
8505 def A(cls, x: int) -> Type[A]: ...
8506 @classmethod
8507 @overload
8508 def A(cls, x: str) -> Type[A]: ...
8509 @classmethod
8510 def A(cls, x: object) -> Type[A]: ...
8511 def B(cls, x: int) -> Type[A]: ... # E: Function "__main__.B.A" is not valid as a type \
8512 # N: Perhaps you need "Callable[...]" or a callback protocol?
8513
8514 [builtins fixtures/classmethod.pyi]
8515
8516 [case testFinalClassWithAbstractAttributes]
8517 from abc import abstractmethod, ABCMeta
8518 from typing import final
8519
8520 @final
8521 class A(metaclass=ABCMeta): # E: Final class __main__.A has abstract attributes "bar", "foo"
8522 @abstractmethod
8523 def foo(self):
8524 pass
8525
8526 @property
8527 @abstractmethod
8528 def bar(self):
8529 pass
8530
8531 [builtins fixtures/property.pyi]
8532
8533 [case testFinalClassWithoutABCMeta]
8534 from abc import abstractmethod
8535 from typing import final
8536
8537 @final
8538 class A(): # E: Final class __main__.A has abstract attributes "bar", "foo"
8539 @abstractmethod
8540 def foo(self):
8541 pass
8542
8543 @property
8544 @abstractmethod
8545 def bar(self):
8546 pass
8547
8548 [builtins fixtures/property.pyi]
8549
8550 [case testFinalClassInheritedAbstractAttributes]
8551 from abc import abstractmethod, ABCMeta
8552 from typing import final
8553
8554 class A(metaclass=ABCMeta):
8555 @abstractmethod
8556 def foo(self):
8557 pass
8558
8559 @final
8560 class B(A): # E: Final class __main__.B has abstract attributes "foo"
8561 pass
8562
8563 [case testUndefinedBaseclassInNestedClass]
8564 class C:
8565 class C1(XX): pass # E: Name "XX" is not defined
8566
8567 [case testArgsKwargsInheritance]
8568 from typing import Any
8569
8570 class A(object):
8571 def f(self, *args: Any, **kwargs: Any) -> int: ...
8572
8573 class B(A):
8574 def f(self, x: int) -> int: ...
8575 [builtins fixtures/dict.pyi]
8576
8577 [case testClassScopeImports]
8578 class Foo:
8579 from mod import plain_function # E: Unsupported class scoped import
8580 from mod import plain_var
8581
8582 reveal_type(Foo.plain_function) # N: Revealed type is "Any"
8583 reveal_type(Foo().plain_function) # N: Revealed type is "Any"
8584
8585 reveal_type(Foo.plain_var) # N: Revealed type is "builtins.int"
8586 reveal_type(Foo().plain_var) # N: Revealed type is "builtins.int"
8587
8588 [file mod.py]
8589 def plain_function(x: int, y: int) -> int: ...
8590 plain_var: int
8591
8592 [case testClassScopeImportModule]
8593 class Foo:
8594 import mod
8595
8596 reveal_type(Foo.mod) # N: Revealed type is "builtins.object"
8597 reveal_type(Foo.mod.foo) # N: Revealed type is "builtins.int"
8598 [file mod.py]
8599 foo: int
8600
8601 [case testClassScopeImportAlias]
8602 class Foo:
8603 from mod import function # E: Unsupported class scoped import
8604 foo = function
8605
8606 from mod import var1
8607 bar = var1
8608
8609 from mod import var2
8610 baz = var2
8611
8612 from mod import var3
8613 qux = var3
8614
8615 reveal_type(Foo.foo) # N: Revealed type is "Any"
8616 reveal_type(Foo.function) # N: Revealed type is "Any"
8617
8618 reveal_type(Foo.bar) # N: Revealed type is "builtins.int"
8619 reveal_type(Foo.var1) # N: Revealed type is "builtins.int"
8620
8621 reveal_type(Foo.baz) # N: Revealed type is "mod.C"
8622 reveal_type(Foo.var2) # N: Revealed type is "mod.C"
8623
8624 reveal_type(Foo.qux) # N: Revealed type is "builtins.int"
8625 reveal_type(Foo.var3) # N: Revealed type is "builtins.int"
8626
8627 [file mod.py]
8628 def function(x: int, y: int) -> int: ...
8629 var1: int
8630
8631 class C: ...
8632 var2: C
8633
8634 A = int
8635 var3: A
8636
8637
8638 [case testClassScopeImportModuleStar]
8639 class Foo:
8640 from mod import * # E: Unsupported class scoped import
8641
8642 reveal_type(Foo.foo) # N: Revealed type is "builtins.int"
8643 reveal_type(Foo.bar) # N: Revealed type is "Any"
8644 reveal_type(Foo.baz) # E: "type[Foo]" has no attribute "baz" \
8645 # N: Revealed type is "Any"
8646
8647 [file mod.py]
8648 foo: int
8649 def bar(x: int) -> int: ...
8650
8651 [case testClassScopeImportAccessibleInMethods]
8652 class A:
8653 import mod
8654 from mod import var
8655
8656 def __new__(cls) -> "A":
8657 reveal_type(cls.mod) # N: Revealed type is "types.ModuleType"
8658 reveal_type(cls.var) # N: Revealed type is "builtins.int"
8659 reveal_type(cls.mod.var) # N: Revealed type is "builtins.int"
8660 return cls()
8661
8662 def pos_or_named_self(self) -> None:
8663 reveal_type(self.mod) # N: Revealed type is "types.ModuleType"
8664 reveal_type(self.var) # N: Revealed type is "builtins.int"
8665 reveal_type(self.mod.var) # N: Revealed type is "builtins.int"
8666
8667 def pos_only_self(self, /) -> None:
8668 reveal_type(self.mod) # N: Revealed type is "types.ModuleType"
8669 reveal_type(self.var) # N: Revealed type is "builtins.int"
8670 reveal_type(self.mod.var) # N: Revealed type is "builtins.int"
8671
8672 @classmethod
8673 def clsmethod(cls) -> None:
8674 reveal_type(cls.mod) # N: Revealed type is "types.ModuleType"
8675 reveal_type(cls.var) # N: Revealed type is "builtins.int"
8676 reveal_type(cls.mod.var) # N: Revealed type is "builtins.int"
8677
8678 [file mod.py]
8679 var = 1
8680 [builtins fixtures/module.pyi]
8681
8682 [case testClassScopeImportFunctionNested]
8683 class Foo:
8684 class Bar:
8685 from mod import baz # E: Unsupported class scoped import
8686
8687 reveal_type(Foo.Bar.baz) # N: Revealed type is "Any"
8688 reveal_type(Foo.Bar().baz) # N: Revealed type is "Any"
8689
8690 [file mod.py]
8691 def baz(x: int) -> int: ...
8692
8693 [case testClassScopeImportUndefined]
8694 class Foo:
8695 from unknown import foo # E: Cannot find implementation or library stub for module named "unknown" \
8696 # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
8697
8698 reveal_type(Foo.foo) # N: Revealed type is "Any"
8699 reveal_type(Foo().foo) # N: Revealed type is "Any"
8700
8701 [case testClassScopeImportWithFollowImports]
8702 # flags: --follow-imports=skip
8703 class Foo:
8704 from mod import foo
8705
8706 reveal_type(Foo().foo) # N: Revealed type is "Any"
8707 [file mod.py]
8708 def foo(x: int, y: int) -> int: ...
8709
8710 [case testClassScopeImportVarious]
8711 class Foo:
8712 from mod1 import foo # E: Unsupported class scoped import
8713 from mod2 import foo
8714
8715 from mod1 import meth1 # E: Unsupported class scoped import
8716 def meth1(self, a: str) -> str: ... # E: Name "meth1" already defined on line 5
8717
8718 def meth2(self, a: str) -> str: ...
8719 from mod1 import meth2 # E: Incompatible import of "meth2" (imported name has type "Callable[[int], int]", local name has type "Callable[[Foo, str], str]")
8720
8721 class Bar:
8722 from mod1 import foo # E: Unsupported class scoped import
8723
8724 import mod1
8725 reveal_type(Foo.foo) # N: Revealed type is "Any"
8726 reveal_type(Bar.foo) # N: Revealed type is "Any"
8727 reveal_type(mod1.foo) # N: Revealed type is "def (x: builtins.int, y: builtins.int) -> builtins.int"
8728
8729 [file mod1.py]
8730 def foo(x: int, y: int) -> int: ...
8731 def meth1(x: int) -> int: ...
8732 def meth2(x: int) -> int: ...
8733 [file mod2.py]
8734 def foo(z: str) -> int: ...
8735
8736
8737 [case testClassScopeImportWithError]
8738 class Foo:
8739 from mod import meth1 # E: Unsupported class scoped import
8740 from mod import meth2 # E: Unsupported class scoped import
8741 from mod import T
8742
8743 reveal_type(Foo.T) # N: Revealed type is "typing.TypeVar"
8744
8745 [file mod.pyi]
8746 from typing import Any, TypeVar, overload
8747
8748 @overload
8749 def meth1(self: Any, y: int) -> int: ...
8750 @overload
8751 def meth1(self: Any, y: str) -> str: ...
8752
8753 T = TypeVar("T")
8754 def meth2(self: Any, y: T) -> T: ...
8755 [builtins fixtures/tuple.pyi]
8756 [typing fixtures/typing-full.pyi]
8757
8758 [case testNewAndInitNoReturn]
8759 from typing import NoReturn
8760
8761 class A:
8762 def __new__(cls) -> NoReturn: ...
8763
8764 class B:
8765 def __init__(self) -> NoReturn: ...
8766
8767 class C:
8768 def __new__(cls) -> "C": ...
8769 def __init__(self) -> NoReturn: ...
8770
8771 class D:
8772 def __new__(cls) -> NoReturn: ...
8773 def __init__(self) -> NoReturn: ...
8774
8775 if object():
8776 reveal_type(A()) # N: Revealed type is "Never"
8777 if object():
8778 reveal_type(B()) # N: Revealed type is "Never"
8779 if object():
8780 reveal_type(C()) # N: Revealed type is "Never"
8781 if object():
8782 reveal_type(D()) # N: Revealed type is "Never"
8783
8784 [case testOverloadedNewAndInitNoReturn]
8785 from typing import NoReturn, overload
8786
8787 class A:
8788 @overload
8789 def __new__(cls) -> NoReturn: ...
8790 @overload
8791 def __new__(cls, a: int) -> "A": ...
8792 def __new__(cls, a: int = ...) -> "A": ...
8793
8794 class B:
8795 @overload
8796 def __init__(self) -> NoReturn: ...
8797 @overload
8798 def __init__(self, a: int) -> None: ...
8799 def __init__(self, a: int = ...) -> None: ...
8800
8801 class C:
8802 def __new__(cls, a: int = ...) -> "C": ...
8803 @overload
8804 def __init__(self) -> NoReturn: ...
8805 @overload
8806 def __init__(self, a: int) -> None: ...
8807 def __init__(self, a: int = ...) -> None: ...
8808
8809 class D:
8810 @overload
8811 def __new__(cls) -> NoReturn: ...
8812 @overload
8813 def __new__(cls, a: int) -> "D": ...
8814 def __new__(cls, a: int = ...) -> "D": ...
8815 @overload
8816 def __init__(self) -> NoReturn: ...
8817 @overload
8818 def __init__(self, a: int) -> None: ...
8819 def __init__(self, a: int = ...) -> None: ...
8820
8821 if object():
8822 reveal_type(A()) # N: Revealed type is "Never"
8823 reveal_type(A(1)) # N: Revealed type is "__main__.A"
8824
8825 if object():
8826 reveal_type(B()) # N: Revealed type is "Never"
8827 reveal_type(B(1)) # N: Revealed type is "__main__.B"
8828
8829 if object():
8830 reveal_type(C()) # N: Revealed type is "Never"
8831 reveal_type(C(1)) # N: Revealed type is "__main__.C"
8832
8833 if object():
8834 reveal_type(D()) # N: Revealed type is "Never"
8835 reveal_type(D(1)) # N: Revealed type is "__main__.D"
8836
8837 [case testClassScopeImportWithWrapperAndError]
8838 class Foo:
8839 from mod import foo # E: Unsupported class scoped import
8840
8841 [file mod.py]
8842 from typing import Any, Callable, TypeVar
8843
8844 FuncT = TypeVar("FuncT", bound=Callable[..., Any])
8845 def identity_wrapper(func: FuncT) -> FuncT:
8846 return func
8847
8848 @identity_wrapper
8849 def foo(self: Any) -> str:
8850 return ""
8851
8852 [case testParentClassWithTypeAliasAndSubclassWithMethod]
8853 from typing import Any, Callable, TypeVar
8854
8855 class Parent:
8856 foo = Callable[..., int]
8857 class bar:
8858 pass
8859 import typing as baz
8860 foobar = TypeVar("foobar")
8861
8862 class Child(Parent):
8863 def foo(self, val: int) -> int: # E: Signature of "foo" incompatible with supertype "Parent" \
8864 # N: Superclass: \
8865 # N: <typing special form> \
8866 # N: Subclass: \
8867 # N: def foo(self, val: int) -> int
8868 return val
8869 def bar(self, val: str) -> str: # E: Signature of "bar" incompatible with supertype "Parent" \
8870 # N: Superclass: \
8871 # N: def bar() -> bar \
8872 # N: Subclass: \
8873 # N: def bar(self, val: str) -> str
8874 return val
8875 def baz(self, val: float) -> float: # E: Signature of "baz" incompatible with supertype "Parent" \
8876 # N: Superclass: \
8877 # N: Module \
8878 # N: Subclass: \
8879 # N: def baz(self, val: float) -> float
8880 return val
8881 def foobar(self) -> bool: # E: Signature of "foobar" incompatible with supertype "Parent" \
8882 # N: Superclass: \
8883 # N: TypeVar \
8884 # N: Subclass: \
8885 # N: def foobar(self) -> bool
8886 return False
8887
8888 x: Parent.foo = lambda: 5
8889 y: Parent.bar = Parent.bar()
8890 z: Parent.baz.Any = 1
8891 child = Child()
8892 a: int = child.foo(1)
8893 b: str = child.bar("abc")
8894 c: float = child.baz(3.4)
8895 d: bool = child.foobar()
8896 [builtins fixtures/module.pyi]
8897 [typing fixtures/typing-full.pyi]
8898
8899 [case testGenericTupleTypeCreation]
8900 from typing import Generic, Tuple, TypeVar
8901
8902 T = TypeVar("T")
8903 S = TypeVar("S")
8904 class C(Tuple[T, S]):
8905 def __init__(self, x: T, y: S) -> None: ...
8906 def foo(self, arg: T) -> S: ...
8907
8908 cis: C[int, str]
8909 reveal_type(cis) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=__main__.C[builtins.int, builtins.str]]"
8910 cii = C(0, 1)
8911 reveal_type(cii) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.C[builtins.int, builtins.int]]"
8912 reveal_type(cis.foo) # N: Revealed type is "def (arg: builtins.int) -> builtins.str"
8913 [builtins fixtures/tuple.pyi]
8914
8915 [case testGenericTupleTypeSubclassing]
8916 from typing import Generic, Tuple, TypeVar, List
8917
8918 T = TypeVar("T")
8919 class C(Tuple[T, T]): ...
8920 class D(C[List[T]]): ...
8921
8922 di: D[int]
8923 reveal_type(di) # N: Revealed type is "tuple[builtins.list[builtins.int], builtins.list[builtins.int], fallback=__main__.D[builtins.int]]"
8924 [builtins fixtures/tuple.pyi]
8925
8926 [case testOverrideAttrWithSettableProperty]
8927 class Foo:
8928 def __init__(self) -> None:
8929 self.x = 42
8930
8931 class Bar(Foo):
8932 @property
8933 def x(self) -> int: ...
8934 @x.setter
8935 def x(self, value: int) -> None: ...
8936 [builtins fixtures/property.pyi]
8937
8938 [case testOverrideAttrWithSettablePropertyAnnotation]
8939 class Foo:
8940 x: int
8941
8942 class Bar(Foo):
8943 @property
8944 def x(self) -> int: ...
8945 @x.setter
8946 def x(self, value: int) -> None: ...
8947 [builtins fixtures/property.pyi]
8948
8949 [case testOverridePropertyDifferentSetterBoth]
8950 class B: ...
8951 class C(B): ...
8952
8953 class B1:
8954 @property
8955 def foo(self) -> str: ...
8956 @foo.setter
8957 def foo(self, x: C) -> None: ...
8958 class C1(B1):
8959 @property
8960 def foo(self) -> str: ...
8961 @foo.setter
8962 def foo(self, x: B) -> None: ...
8963
8964 class B2:
8965 @property
8966 def foo(self) -> str: ...
8967 @foo.setter
8968 def foo(self, x: B) -> None: ...
8969 class C2(B2):
8970 @property
8971 def foo(self) -> str: ...
8972 @foo.setter # E: Incompatible override of a setter type \
8973 # N: (base class "B2" defined the type as "B", \
8974 # N: override has type "C") \
8975 # N: Setter types should behave contravariantly
8976 def foo(self, x: C) -> None: ...
8977
8978 class B3:
8979 @property
8980 def foo(self) -> C: ...
8981 @foo.setter
8982 def foo(self, x: C) -> None: ...
8983 class C3(B3):
8984 @property
8985 def foo(self) -> C: ...
8986 @foo.setter
8987 def foo(self, x: B) -> None: ...
8988
8989 class B4:
8990 @property
8991 def foo(self) -> C: ...
8992 @foo.setter
8993 def foo(self, x: B) -> None: ...
8994 class C4(B4):
8995 @property
8996 def foo(self) -> C: ...
8997 @foo.setter # E: Incompatible override of a setter type \
8998 # N: (base class "B4" defined the type as "B", \
8999 # N: override has type "C") \
9000 # N: Setter types should behave contravariantly
9001 def foo(self, x: C) -> None: ...
9002
9003 class B5:
9004 @property
9005 def foo(self) -> str: ...
9006 @foo.setter
9007 def foo(self, x: B) -> None: ...
9008 class C5(B5):
9009 @property # E: Signature of "foo" incompatible with supertype "B5" \
9010 # N: Superclass: \
9011 # N: str \
9012 # N: Subclass: \
9013 # N: C
9014 def foo(self) -> C: ...
9015 @foo.setter # E: Incompatible override of a setter type \
9016 # N: (base class "B5" defined the type as "B", \
9017 # N: override has type "str")
9018 def foo(self, x: str) -> None: ...
9019
9020 class B6:
9021 @property
9022 def foo(self) -> B: ...
9023 @foo.setter
9024 def foo(self, x: B) -> None: ...
9025 class C6(B6):
9026 @property
9027 def foo(self) -> C: ...
9028 @foo.setter
9029 def foo(self, x: B) -> None: ...
9030 [builtins fixtures/property.pyi]
9031
9032 [case testOverridePropertyDifferentSetterVarSuper]
9033 class B: ...
9034 class C(B): ...
9035
9036 class B1:
9037 foo: B
9038 class C1(B1):
9039 @property
9040 def foo(self) -> B: ...
9041 @foo.setter # E: Incompatible override of a setter type \
9042 # N: (base class "B1" defined the type as "B", \
9043 # N: override has type "C") \
9044 # N: Setter types should behave contravariantly
9045 def foo(self, x: C) -> None: ...
9046
9047 class B2:
9048 foo: C
9049 class C2(B2):
9050 @property
9051 def foo(self) -> C: ...
9052 @foo.setter
9053 def foo(self, x: B) -> None: ...
9054
9055 class B3:
9056 foo: B
9057 class C3(B3):
9058 @property
9059 def foo(self) -> C: ...
9060 @foo.setter
9061 def foo(self, x: B) -> None: ...
9062 [builtins fixtures/property.pyi]
9063
9064 [case testOverridePropertyDifferentSetterVarSub]
9065 class B: ...
9066 class C(B): ...
9067
9068 class B1:
9069 @property
9070 def foo(self) -> B: ...
9071 @foo.setter
9072 def foo(self, x: C) -> None: ...
9073 class C1(B1):
9074 foo: C
9075
9076 class B2:
9077 @property
9078 def foo(self) -> B: ...
9079 @foo.setter
9080 def foo(self, x: C) -> None: ...
9081 class C2(B2):
9082 foo: B
9083
9084 class B3:
9085 @property
9086 def foo(self) -> C: ...
9087 @foo.setter
9088 def foo(self, x: B) -> None: ...
9089 class C3(B3):
9090 foo: C # E: Incompatible override of a setter type \
9091 # N: (base class "B3" defined the type as "B", \
9092 # N: override has type "C") \
9093 # N: Setter types should behave contravariantly
9094 [builtins fixtures/property.pyi]
9095
9096 [case testOverridePropertyInvalidSetter]
9097 class B1:
9098 @property
9099 def foo(self) -> int: ...
9100 @foo.setter
9101 def foo(self, x: str) -> None: ...
9102 class C1(B1):
9103 @property
9104 def foo(self) -> int: ...
9105 @foo.setter
9106 def foo(self) -> None: ... # E: Invalid property setter signature
9107
9108 class B2:
9109 @property
9110 def foo(self) -> int: ...
9111 @foo.setter
9112 def foo(self) -> None: ... # E: Invalid property setter signature
9113 class C2(B2):
9114 @property
9115 def foo(self) -> int: ...
9116 @foo.setter
9117 def foo(self, x: str) -> None: ...
9118
9119 class B3:
9120 @property
9121 def foo(self) -> int: ...
9122 @foo.setter
9123 def foo(self) -> None: ... # E: Invalid property setter signature
9124 class C3(B3):
9125 foo: int
9126 [builtins fixtures/property.pyi]
9127
9128 [case testOverridePropertyGeneric]
9129 from typing import TypeVar, Generic
9130
9131 T = TypeVar("T")
9132
9133 class B1(Generic[T]):
9134 @property
9135 def foo(self) -> int: ...
9136 @foo.setter
9137 def foo(self, x: T) -> None: ...
9138 class C1(B1[str]):
9139 @property
9140 def foo(self) -> int: ...
9141 @foo.setter # E: Incompatible override of a setter type \
9142 # N: (base class "B1" defined the type as "str", \
9143 # N: override has type "int")
9144 def foo(self, x: int) -> None: ...
9145
9146 class B2:
9147 @property
9148 def foo(self) -> int: ...
9149 @foo.setter
9150 def foo(self: T, x: T) -> None: ...
9151 class C2(B2):
9152 @property
9153 def foo(self) -> int: ...
9154 @foo.setter # E: Incompatible override of a setter type \
9155 # N: (base class "B2" defined the type as "C2", \
9156 # N: override has type "int")
9157 def foo(self, x: int) -> None: ...
9158 [builtins fixtures/property.pyi]
9159
9160 [case testOverrideMethodProperty]
9161 class B:
9162 def foo(self) -> int:
9163 ...
9164 class C(B):
9165 @property
9166 def foo(self) -> int: # E: Signature of "foo" incompatible with supertype "B" \
9167 # N: Superclass: \
9168 # N: def foo(self) -> int \
9169 # N: Subclass: \
9170 # N: int
9171 ...
9172 [builtins fixtures/property.pyi]
9173
9174 [case testOverridePropertyMethod]
9175 class B:
9176 @property
9177 def foo(self) -> int:
9178 ...
9179 class C(B):
9180 def foo(self) -> int: # E: Signature of "foo" incompatible with supertype "B" \
9181 # N: Superclass: \
9182 # N: int \
9183 # N: Subclass: \
9184 # N: def foo(self) -> int
9185 ...
9186 [builtins fixtures/property.pyi]
9187
9188 [case testAllowArgumentAsBaseClass]
9189 from typing import Any, Type
9190
9191 def e(b) -> None:
9192 class D(b): ...
9193
9194 def f(b: Any) -> None:
9195 class D(b): ...
9196
9197 def g(b: Type[Any]) -> None:
9198 class D(b): ...
9199
9200 def h(b: type) -> None:
9201 class D(b): ...
9202
9203 [case testNoCrashOnSelfWithForwardRefGenericClass]
9204 from typing import Generic, Sequence, TypeVar, Self
9205
9206 _T = TypeVar('_T', bound="Foo")
9207
9208 class Foo:
9209 foo: int
9210
9211 class Element(Generic[_T]):
9212 elements: Sequence[Self]
9213
9214 class Bar(Foo): ...
9215 e: Element[Bar]
9216 reveal_type(e.elements) # N: Revealed type is "typing.Sequence[__main__.Element[__main__.Bar]]"
9217
9218 [case testIterableUnpackingWithGetAttr]
9219 from typing import Union, Tuple
9220
9221 class C:
9222 def __getattr__(self, name):
9223 pass
9224
9225 class D:
9226 def f(self) -> C:
9227 return C()
9228
9229 def g(self) -> None:
9230 # iter(x) looks up `__iter__` on the type of x rather than x itself,
9231 # so this is correct behaviour.
9232 # Instances of C should not be treated as being iterable,
9233 # despite having a __getattr__ method
9234 # that could allow for arbitrary attributes to be accessed on instances,
9235 # since `type(C()).__iter__` still raises AttributeError at runtime,
9236 # and that's what matters.
9237 a, b = self.f() # E: "C" has no attribute "__iter__" (not iterable)
9238 [builtins fixtures/tuple.pyi]
9239
9240 [case testUsingNumbersType]
9241 from numbers import Number, Complex, Real, Rational, Integral
9242
9243 def f1(x: Number) -> None: pass
9244 f1(1) # E: Argument 1 to "f1" has incompatible type "int"; expected "Number" \
9245 # N: Types from "numbers" are not supported for static type checking \
9246 # N: See https://peps.python.org/pep-0484/#the-numeric-tower \
9247 # N: Consider using a protocol instead, such as typing.SupportsFloat
9248
9249 def f2(x: Complex) -> None: pass
9250 f2(1) # E: Argument 1 to "f2" has incompatible type "int"; expected "Complex" \
9251 # N: Types from "numbers" are not supported for static type checking \
9252 # N: See https://peps.python.org/pep-0484/#the-numeric-tower \
9253 # N: Consider using a protocol instead, such as typing.SupportsFloat
9254
9255 def f3(x: Real) -> None: pass
9256 f3(1) # E: Argument 1 to "f3" has incompatible type "int"; expected "Real" \
9257 # N: Types from "numbers" are not supported for static type checking \
9258 # N: See https://peps.python.org/pep-0484/#the-numeric-tower \
9259 # N: Consider using a protocol instead, such as typing.SupportsFloat
9260
9261 def f4(x: Rational) -> None: pass
9262 f4(1) # E: Argument 1 to "f4" has incompatible type "int"; expected "Rational" \
9263 # N: Types from "numbers" are not supported for static type checking \
9264 # N: See https://peps.python.org/pep-0484/#the-numeric-tower \
9265 # N: Consider using a protocol instead, such as typing.SupportsFloat
9266
9267 def f5(x: Integral) -> None: pass
9268 f5(1) # E: Argument 1 to "f5" has incompatible type "int"; expected "Integral" \
9269 # N: Types from "numbers" are not supported for static type checking \
9270 # N: See https://peps.python.org/pep-0484/#the-numeric-tower \
9271 # N: Consider using a protocol instead, such as typing.SupportsFloat
9272
9273 [case testImplicitClassScopedNames]
9274 class C:
9275 reveal_type(__module__) # N: Revealed type is "builtins.str"
9276 reveal_type(__qualname__) # N: Revealed type is "builtins.str"
9277 def f(self) -> None:
9278 __module__ # E: Name "__module__" is not defined
9279 __qualname__ # E: Name "__qualname__" is not defined
9280
9281 x: __module__ # E: Variable "__main__.C.__module__" is not valid as a type \
9282 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
9283 y: __qualname__ # E: Variable "__main__.C.__qualname__" is not valid as a type \
9284 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
9285
9286 [case testPropertySetterType]
9287 class A:
9288 @property
9289 def f(self) -> int:
9290 return 1
9291 @f.setter
9292 def f(self, x: str) -> None:
9293 pass
9294 a = A()
9295 a.f = '' # OK
9296 reveal_type(a.f) # N: Revealed type is "builtins.int"
9297 a.f = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "str")
9298 reveal_type(a.f) # N: Revealed type is "builtins.int"
9299 [builtins fixtures/property.pyi]
9300
9301 [case testPropertySetterTypeGeneric]
9302 from typing import TypeVar, Generic, List
9303
9304 T = TypeVar("T")
9305
9306 class B(Generic[T]):
9307 @property
9308 def foo(self) -> int: ...
9309 @foo.setter
9310 def foo(self, x: T) -> None: ...
9311
9312 class C(B[List[T]]): ...
9313
9314 a = C[str]()
9315 a.foo = ["foo", "bar"]
9316 reveal_type(a.foo) # N: Revealed type is "builtins.int"
9317 a.foo = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "list[str]")
9318 reveal_type(a.foo) # N: Revealed type is "builtins.int"
9319 [builtins fixtures/property.pyi]
9320
9321 [case testPropertyDeleterNoSetterOK]
9322 class C:
9323 @property
9324 def x(self) -> int:
9325 return 0
9326 @x.deleter
9327 def x(self) -> None:
9328 pass
9329 [builtins fixtures/property.pyi]
9330
9331 [case testPropertySetterSuperclassDeferred]
9332 from typing import Callable, TypeVar
9333
9334 class B:
9335 def __init__(self) -> None:
9336 self.foo = f()
9337
9338 class C(B):
9339 @property
9340 def foo(self) -> str: ...
9341 @foo.setter # E: Incompatible override of a setter type \
9342 # N: (base class "B" defined the type as "str", \
9343 # N: override has type "int")
9344 def foo(self, x: int) -> None: ...
9345
9346 T = TypeVar("T")
9347 def deco(fn: Callable[[], list[T]]) -> Callable[[], T]: ...
9348
9349 @deco
9350 def f() -> list[str]: ...
9351 [builtins fixtures/property.pyi]
9352
9353 [case testPropertySetterSuperclassDeferred2]
9354 import a
9355 [file a.py]
9356 import b
9357 class D(b.C):
9358 @property
9359 def foo(self) -> str: ...
9360 @foo.setter # E: Incompatible override of a setter type \
9361 # N: (base class "C" defined the type as "str", \
9362 # N: override has type "int")
9363 def foo(self, x: int) -> None: ...
9364 [file b.py]
9365 from a import D
9366 class C:
9367 @property
9368 def foo(self) -> str: ...
9369 @foo.setter
9370 def foo(self, x: str) -> None: ...
9371 [builtins fixtures/property.pyi]
9372
9373 [case testPropertySetterDecorated]
9374 from typing import Callable, TypeVar, Generic
9375
9376 class B:
9377 def __init__(self) -> None:
9378 self.foo: str
9379 self.bar: int
9380
9381 class C(B):
9382 @property
9383 def foo(self) -> str: ...
9384 @foo.setter # E: Incompatible override of a setter type \
9385 # N: (base class "B" defined the type as "str", \
9386 # N: override has type "int")
9387 @deco
9388 def foo(self, x: int, y: int) -> None: ...
9389
9390 @property
9391 def bar(self) -> int: ...
9392 @bar.setter
9393 @deco
9394 def bar(self, x: int, y: int) -> None: ...
9395
9396 @property
9397 def baz(self) -> int: ...
9398 @baz.setter
9399 @deco_untyped
9400 def baz(self, x: int) -> None: ...
9401
9402 @property
9403 def tricky(self) -> int: ...
9404 @tricky.setter
9405 @deco_instance
9406 def tricky(self, x: int) -> None: ...
9407
9408 c: C
9409 c.baz = "yes" # OK, because of untyped decorator
9410 c.tricky = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "list[int]")
9411
9412 T = TypeVar("T")
9413 def deco(fn: Callable[[T, int, int], None]) -> Callable[[T, int], None]: ...
9414 def deco_untyped(fn): ...
9415
9416 class Wrapper(Generic[T]):
9417 def __call__(self, s: T, x: list[int]) -> None: ...
9418 def deco_instance(fn: Callable[[T, int], None]) -> Wrapper[T]: ...
9419 [builtins fixtures/property.pyi]
9420
9421 [case testPropertyDeleterBodyChecked]
9422 class C:
9423 @property
9424 def foo(self) -> int: ...
9425 @foo.deleter
9426 def foo(self) -> None:
9427 1() # E: "int" not callable
9428
9429 @property
9430 def bar(self) -> int: ...
9431 @bar.setter
9432 def bar(self, x: str) -> None: ...
9433 @bar.deleter
9434 def bar(self) -> None:
9435 1() # E: "int" not callable
9436 [builtins fixtures/property.pyi]
9437
9438 [case testSettablePropertyGetterDecorated]
9439 from typing import Callable, TypeVar, Generic
9440
9441 class C:
9442 @property
9443 @deco
9444 def foo(self, ok: int) -> str: ...
9445 @foo.setter
9446 def foo(self, x: str) -> None: ...
9447
9448 @property
9449 @deco_instance
9450 def bar(self, ok: int) -> int: ...
9451 @bar.setter
9452 def bar(self, x: int) -> None: ...
9453
9454 @property
9455 @deco_untyped
9456 def baz(self) -> int: ...
9457 @baz.setter
9458 def baz(self, x: int) -> None: ...
9459
9460 c: C
9461 reveal_type(c.foo) # N: Revealed type is "builtins.list[builtins.str]"
9462 reveal_type(c.bar) # N: Revealed type is "builtins.list[builtins.int]"
9463 reveal_type(c.baz) # N: Revealed type is "Any"
9464
9465 T = TypeVar("T")
9466 R = TypeVar("R")
9467 def deco(fn: Callable[[T, int], R]) -> Callable[[T], list[R]]: ...
9468 def deco_untyped(fn): ...
9469
9470 class Wrapper(Generic[T, R]):
9471 def __call__(self, s: T) -> list[R]: ...
9472 def deco_instance(fn: Callable[[T, int], R]) -> Wrapper[T, R]: ...
9473 [builtins fixtures/property.pyi]
9474
9475 [case testOverridePropertyWithDescriptor]
9476 from typing import Any
9477
9478 class StrProperty:
9479 def __get__(self, instance: Any, owner: Any) -> str: ...
9480
9481 class Base:
9482 @property
9483 def id(self) -> str: ...
9484
9485 class BadBase:
9486 @property
9487 def id(self) -> int: ...
9488
9489 class Derived(Base):
9490 id = StrProperty()
9491
9492 class BadDerived(BadBase):
9493 id = StrProperty() # E: Incompatible types in assignment (expression has type "str", base class "BadBase" defined the type as "int")
9494 [builtins fixtures/property.pyi]
9495
9496 [case testLambdaInOverrideInference]
9497 class B:
9498 def f(self, x: int) -> int: ...
9499 class C(B):
9500 f = lambda s, x: x
9501
9502 reveal_type(C().f) # N: Revealed type is "def (x: builtins.int) -> builtins.int"
9503
9504 [case testGenericDecoratorInOverrideInference]
9505 from typing import Any, Callable, TypeVar
9506 from typing_extensions import ParamSpec, Concatenate
9507
9508 P = ParamSpec("P")
9509 T = TypeVar("T")
9510 def wrap(f: Callable[Concatenate[Any, P], T]) -> Callable[Concatenate[Any, P], T]: ...
9511
9512 class Base:
9513 def g(self, a: int) -> int:
9514 return a + 1
9515
9516 class Derived(Base):
9517 def _g(self, a: int) -> int:
9518 return a + 2
9519 g = wrap(_g)
9520
9521 reveal_type(Derived().g) # N: Revealed type is "def (a: builtins.int) -> builtins.int"
9522 [builtins fixtures/paramspec.pyi]
9523
9524 [case testClassVarOverrideWithSubclass]
9525 class A: ...
9526 class B(A): ...
9527 class AA:
9528 cls = A
9529 class BB(AA):
9530 cls = B
9531
9532 [case testSelfReferenceWithinMethodFunction]
9533 class B:
9534 x: str
9535 class C(B):
9536 def meth(self) -> None:
9537 def cb() -> None:
9538 self.x: int = 1 # E: Incompatible types in assignment (expression has type "int", base class "B" defined the type as "str")
9539
9540 [case testOverloadedDescriptorSelected]
9541 from typing import Generic, TypeVar, Any, overload
9542
9543 T_co = TypeVar("T_co", covariant=True)
9544 class Field(Generic[T_co]):
9545 @overload
9546 def __get__(self: Field[bool], instance: None, owner: Any) -> BoolField: ...
9547 @overload
9548 def __get__(self: Field[int], instance: None, owner: Any) -> NumField: ...
9549 @overload
9550 def __get__(self: Field[Any], instance: None, owner: Any) -> AnyField[T_co]: ...
9551 @overload
9552 def __get__(self, instance: Any, owner: Any) -> T_co: ...
9553
9554 def __get__(self, instance: Any, owner: Any) -> Any:
9555 pass
9556
9557 class BoolField(Field[bool]): ...
9558 class NumField(Field[int]): ...
9559 class AnyField(Field[T_co]): ...
9560 class Custom: ...
9561
9562 class Fields:
9563 bool_f: Field[bool]
9564 int_f: Field[int]
9565 custom_f: Field[Custom]
9566
9567 reveal_type(Fields.bool_f) # N: Revealed type is "__main__.BoolField"
9568 reveal_type(Fields.int_f) # N: Revealed type is "__main__.NumField"
9569 reveal_type(Fields.custom_f) # N: Revealed type is "__main__.AnyField[__main__.Custom]"
9570
9571 [case testRecursivePropertyWithInvalidSetterNoCrash]
9572 class NoopPowerResource:
9573 _hardware_type: int
9574
9575 @property
9576 def hardware_type(self) -> int:
9577 return self._hardware_type
9578
9579 @hardware_type.setter
9580 def hardware_type(self) -> None: # E: Invalid property setter signature
9581 self.hardware_type = None # Note: intentionally recursive
9582 [builtins fixtures/property.pyi]
9583
9584 [case testOverrideErrorReportingNoDuplicates]
9585 from typing import Callable, TypeVar
9586
9587 def nested() -> None:
9588 class B:
9589 def meth(self, x: str) -> int: ...
9590 class C(B):
9591 def meth(self) -> str: # E: Signature of "meth" incompatible with supertype "B" \
9592 # N: Superclass: \
9593 # N: def meth(self, x: str) -> int \
9594 # N: Subclass: \
9595 # N: def meth(self) -> str
9596 pass
9597 x = defer()
9598
9599 T = TypeVar("T")
9600 def deco(fn: Callable[[], T]) -> Callable[[], list[T]]: ...
9601
9602 @deco
9603 def defer() -> int: ...
9604 [builtins fixtures/list.pyi]
9605
9606 [case testPropertyAllowsDeleterBeforeSetter]
9607 class C:
9608 @property
9609 def foo(self) -> str: ...
9610 @foo.deleter
9611 def foo(self) -> None: ...
9612 @foo.setter
9613 def foo(self, val: int) -> None: ...
9614
9615 @property
9616 def bar(self) -> int: ...
9617 @bar.deleter
9618 def bar(self) -> None: ...
9619 @bar.setter
9620 def bar(self, value: int, val: int) -> None: ... # E: Invalid property setter signature
9621
9622 C().foo = "no" # E: Incompatible types in assignment (expression has type "str", variable has type "int")
9623 C().bar = "fine"
9624 [builtins fixtures/property.pyi]
9625
9626 [case testCorrectConstructorTypeWithAnyFallback]
9627 from typing import Generic, TypeVar
9628
9629 class B(Unknown): # type: ignore
9630 def __init__(self) -> None: ...
9631 class C(B): ...
9632
9633 reveal_type(C) # N: Revealed type is "def () -> __main__.C"
9634
9635 T = TypeVar("T")
9636 class BG(Generic[T], Unknown): # type: ignore
9637 def __init__(self) -> None: ...
9638 class CGI(BG[int]): ...
9639 class CGT(BG[T]): ...
9640
9641 reveal_type(CGI) # N: Revealed type is "def () -> __main__.CGI"
9642 reveal_type(CGT) # N: Revealed type is "def [T] () -> __main__.CGT[T`1]"
9643
9644 [case testSettablePropertyAlias]
9645 from typing import Any, TypeVar
9646
9647 class A:
9648 @property
9649 def prop(self: Any) -> str: ...
9650 @prop.setter
9651 def prop(self, val: str) -> None: ...
9652
9653 T = TypeVar("T")
9654 class AT:
9655 @property
9656 def prop(self: T) -> T: ...
9657 @prop.setter
9658 def prop(self: T, val: list[T]) -> None: ...
9659
9660 class B:
9661 prop: str
9662 prop_t: str
9663
9664 class C(B):
9665 prop = A.prop
9666 prop_t = AT.prop # E: Incompatible types in assignment (expression has type "C", base class "B" defined the type as "str")
9667
9668 reveal_type(C().prop) # N: Revealed type is "builtins.str"
9669 C().prop = "no" # E: Invalid self argument "C" to attribute function "prop" with type "Callable[[A, str], None]"
9670 reveal_type(C().prop_t) # N: Revealed type is "__main__.C"
9671 C().prop_t = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "list[C]")
9672 [builtins fixtures/property.pyi]
9673
9674 [case testClassEqDecoratedAbstractNote]
9675 from abc import abstractmethod
9676
9677 class C:
9678 @abstractmethod
9679 def __eq__(self, other: C) -> bool: ...
9680 [builtins fixtures/plugin_attrs.pyi]
9681 [out]
9682 main:5: error: Argument 1 of "__eq__" is incompatible with supertype "builtins.object"; supertype defines the argument type as "object"
9683 main:5: note: This violates the Liskov substitution principle
9684 main:5: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
9685 main:5: note: It is recommended for "__eq__" to work with arbitrary objects, for example:
9686 main:5: note: def __eq__(self, other: object) -> bool:
9687 main:5: note: if not isinstance(other, C):
9688 main:5: note: return NotImplemented
9689 main:5: note: return <logic to compare two C instances>
9690
9691 [case testLambdaInAttributeCallValue]
9692 # https://github.com/python/mypy/issues/19632
9693 import foo
9694
9695 def nop(fn: object) -> foo.Bar:
9696 return foo.Bar()
9697
9698 class Bar:
9699 foo: foo.Bar = nop(
9700 lambda: 0
9701 )
9702 [file foo.py]
9703 class Bar:
9704 ...
9705
9706 [case testConstructorWithoutStrictOptionalNoCache]
9707 import mod
9708 a = mod.NT(x=None) # OK
9709
9710 [file typ.py]
9711 from typing import NamedTuple, Optional
9712 NT = NamedTuple("NT", [("x", Optional[str])])
9713
9714 [file mod.py]
9715 # mypy: no-strict-optional
9716 from typ import NT
9717
9718 def f() -> NT:
9719 return NT(x='')
9720 [builtins fixtures/tuple.pyi]
9721
9722 [case testClassNestedInFunctionNotLeaking]
9723 from a import X # E: Module "a" has no attribute "X"
9724 reveal_type(X) # N: Revealed type is "Any"
9725 [file a.py]
9726 def f() -> None:
9727 class X:
9728 ...
9729 undefined # E: Name "undefined" is not defined