← Back to index
constructors_call_metaclass.py
True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 2
FP: 0
FN: 0
Optional: 0 / 0
1
"""
2
Tests
the
evaluation
of
calls
to
constructors
when
there
is
a
custom
3
metaclass
with
a
__call__
method
.
4
"""
5
6
from
typing
import
NoReturn
,
Self
,
TypeVar
,
assert_type
7
8
# Specification: https://typing.readthedocs.io/en/latest/spec/constructors.html#constructor-calls
9
10
# Metaclass __call__ method: https://typing.readthedocs.io/en/latest/spec/constructors.html#metaclass-call-method
11
12
13
class
Meta1
(
type
):
14
def
__call__
(
cls
,
*
args
,
**
kwargs
)
->
NoReturn
:
15
raise
TypeError
(
"Cannot instantiate class"
)
16
17
18
class
Class1
(
metaclass
=
Meta1
):
19
def
__new__
(
cls
,
x
:
int
)
->
Self
:
20
return
super
()
.
__new__
(
cls
)
21
22
23
# This needs to be in a separate scope, because some type checkers might mark
24
# the statements after it as unreachable.
25
if
bool
():
26
assert_type
(
Class1
(),
NoReturn
)
27
28
29
class
Meta2
(
type
):
30
def
__call__
(
cls
,
*
args
,
**
kwargs
)
->
"int | Meta2"
:
31
return
1
32
33
34
class
Class2
(
metaclass
=
Meta2
):
35
def
__new__
(
cls
,
x
:
int
)
->
Self
:
36
return
super
()
.
__new__
(
cls
)
37
38
39
assert_type
(
Class2
(),
int
|
Meta2
)
40
41
T
=
TypeVar
(
"T"
)
42
43
44
class
Meta3
(
type
):
45
def
__call__
(
cls
:
type
[
T
],
*
args
,
**
kwargs
)
->
T
:
46
return
type
.
__call__
(
cls
,
*
args
,
**
kwargs
)
47
48
49
class
Class3
(
metaclass
=
Meta3
):
50
def
__new__
(
cls
,
x
:
int
)
->
Self
:
51
return
super
()
.
__new__
(
cls
)
52
53
54
Class3
()
# E: Missing argument for 'x' parameter in __new__
[missing-argument] No argument provided for required parameter `x` of function `__new__`
55
assert_type
(
Class3
(
1
),
Class3
)
56
57
58
class
Meta4
(
type
):
59
def
__call__
(
cls
,
*
args
,
**
kwargs
):
60
return
type
.
__call__
(
cls
,
*
args
,
**
kwargs
)
61
62
63
class
Class4
(
metaclass
=
Meta4
):
64
def
__new__
(
cls
,
x
:
int
)
->
Self
:
65
return
super
()
.
__new__
(
cls
)
66
67
68
Class4
()
# E: Missing argument for 'x' parameter in __new__
[missing-argument] No argument provided for required parameter `x` of function `__new__`
69
assert_type
(
Class4
(
1
),
Class4
)