← Back to index
dataclasses_descriptors.py
True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 0
FP: 2
FN: 0
Optional: 0 / 0
1
"""
2
Tests
the
handling
of
descriptors
within
a
dataclass
.
3
"""
4
5
# This portion of the dataclass spec is under-specified in the documentation,
6
# but its behavior can be determined from the runtime implementation.
7
8
from
dataclasses
import
dataclass
9
from
typing
import
Any
,
Generic
,
TypeVar
,
assert_type
,
overload
10
11
T
=
TypeVar
(
"T"
)
12
13
14
class
Desc1
:
15
@overload
16
def
__get__
(
self
,
__obj
:
None
,
__owner
:
Any
)
->
"Desc1"
:
17
...
18
19
@overload
20
def
__get__
(
self
,
__obj
:
object
,
__owner
:
Any
)
->
int
:
21
...
22
23
def
__get__
(
self
,
__obj
:
object
|
None
,
__owner
:
Any
)
->
"int | Desc1"
:
24
raise
NotImplementedError
25
26
def
__set__
(
self
,
__obj
:
object
,
__value
:
int
)
->
None
:
27
...
28
29
30
@dataclass
31
class
DC1
:
32
y
:
Desc1
=
Desc1
()
33
34
35
dc1
=
DC1
(
3
)
36
37
assert_type
(
dc1
.
y
,
int
)
38
assert_type
(
DC1
.
y
,
Desc1
)
39
40
41
class
Desc2
(
Generic
[
T
]):
42
@overload
43
def
__get__
(
self
,
instance
:
None
,
owner
:
Any
)
->
list
[
T
]:
44
...
45
46
@overload
47
def
__get__
(
self
,
instance
:
object
,
owner
:
Any
)
->
T
:
48
...
49
50
def
__get__
(
self
,
instance
:
object
|
None
,
owner
:
Any
)
->
list
[
T
]
|
T
:
51
raise
NotImplementedError
52
53
54
@dataclass
55
class
DC2
:
56
x
:
Desc2
[
int
]
57
y
:
Desc2
[
str
]
58
z
:
Desc2
[
str
]
=
Desc2
()
59
60
61
assert_type
(
DC2
.
x
,
list
[
int
])
62
assert_type
(
DC2
.
y
,
list
[
str
])
63
assert_type
(
DC2
.
z
,
list
[
str
])
64
65
dc2
=
DC2
(
Desc2
(),
Desc2
(),
Desc2
())
66
assert_type
(
dc2
.
x
,
int
)
Unexpected error [type-assertion-failure] Type `int` does not match asserted type `int | Desc2[int]`
67
assert_type
(
dc2
.
y
,
str
)
Unexpected error [type-assertion-failure] Type `str` does not match asserted type `str | Desc2[str]`
68
assert_type
(
dc2
.
z
,
str
)