-
Notifications
You must be signed in to change notification settings - Fork 293
Expand file tree
/
Copy pathdataclasses_descriptors.py
More file actions
68 lines (46 loc) · 1.38 KB
/
dataclasses_descriptors.py
File metadata and controls
68 lines (46 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""
Tests the handling of descriptors within a dataclass.
"""
# This portion of the dataclass spec is under-specified in the documentation,
# but its behavior can be determined from the runtime implementation.
from dataclasses import dataclass
from typing import Any, Generic, TypeVar, assert_type, overload
T = TypeVar("T")
class Desc1:
@overload
def __get__(self, __obj: None, __owner: Any) -> "Desc1":
...
@overload
def __get__(self, __obj: object, __owner: Any) -> int:
...
def __get__(self, __obj: object | None, __owner: Any) -> "int | Desc1":
raise NotImplementedError
def __set__(self, __obj: object, __value: int) -> None:
...
@dataclass
class DC1:
y: Desc1 = Desc1()
dc1 = DC1(3)
assert_type(dc1.y, int)
assert_type(DC1.y, Desc1)
class Desc2(Generic[T]):
@overload
def __get__(self, instance: None, owner: Any) -> list[T]:
...
@overload
def __get__(self, instance: object, owner: Any) -> T:
...
def __get__(self, instance: object | None, owner: Any) -> list[T] | T:
raise NotImplementedError
@dataclass
class DC2:
x: Desc2[int]
y: Desc2[str]
z: Desc2[str] = Desc2()
assert_type(DC2.x, list[int])
assert_type(DC2.y, list[str])
assert_type(DC2.z, list[str])
dc2 = DC2(Desc2(), Desc2(), Desc2())
assert_type(dc2.x, int)
assert_type(dc2.y, str)
assert_type(dc2.z, str)