← Back to index

constructors_call_type.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 5
FP: 0
FN: 3
Optional: 0 / 0
1"""
2Tests the evaluation of calls to constructors when the type is type[T].
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/constructors.html#constructor-calls-for-type-t
6
7# > When a value of type type[T] (where T is a concrete class or a type
8# > variable) is called, a type checker should evaluate the constructor
9# > call as if it is being made on the class T.
11from typing import Self, TypeVar
14T = TypeVar("T")
17class Meta1(type):
18 # Ignore possible errors related to incompatible override
19 def __call__(cls: type[T], x: int, y: str) -> T: # type: ignore
[unused-type-ignore-comment] Unused blanket `type: ignore` directive
20 return type.__call__(cls)
23class Class1(metaclass=Meta1):
24 def __new__(cls, *args, **kwargs) -> Self:
25 return super().__new__(*args, **kwargs)
28def func1(cls: type[Class1]):
29 cls(x=1, y="") # OK
30 cls() # E
Expected a ty diagnostic for this line
33class Class2:
34 def __new__(cls, x: int, y: str) -> Self:
35 return super().__new__(cls)
38def func2(cls: type[Class2]):
39 cls(x=1, y="") # OK
40 cls() # E
[missing-argument] No arguments provided for required parameters `x`, `y` of function `__new__`
43class Class3:
44 def __init__(self, x: int, y: str) -> None:
45 pass
48def func3(cls: type[Class3]):
49 cls(x=1, y="") # OK
50 cls() # E
[missing-argument] No arguments provided for required parameters `x`, `y` of bound method `__init__`
53class Class4:
54 pass
57def func4(cls: type[Class4]):
58 cls() # OK
59 cls(1) # E
[too-many-positional-arguments] Too many positional arguments to bound method `__init__`: expected 1, got 2
62def func5(cls: type[T]):
63 cls() # OK
64 cls(1) # E
Expected a ty diagnostic for this line
67T1 = TypeVar("T1", bound=Class1)
70def func6(cls: type[T1]):
71 cls(x=1, y="") # OK
72 cls() # E
Expected a ty diagnostic for this line
75T2 = TypeVar("T2", bound=Class2)
78def func7(cls: type[T2]):
79 cls(1, "") # OK
80 cls(x=1, y="") # OK
81 cls(1) # E
[missing-argument] No argument provided for required parameter `y` of function `__new__`
82 cls(1, 2) # E
[invalid-argument-type] Argument to function `__new__` is incorrect: Expected `str`, found `Literal[2]`