-
Notifications
You must be signed in to change notification settings - Fork 303
Expand file tree
/
Copy pathdataclasses_descriptors.py
More file actions
74 lines (53 loc) · 1.85 KB
/
Copy pathdataclasses_descriptors.py
File metadata and controls
74 lines (53 loc) · 1.85 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
69
70
71
72
73
74
"""
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()
# Runtime behavior involving non-data descriptors in dataclasses is
# currently under-specified and differs across type checkers and runtime
# implementations.
#
# In particular:
# - DC2.x and DC2.y raise AttributeError at runtime because no descriptor
# instance is stored in the class dictionary for those fields.
# - dc2.x and dc2.y evaluate to the stored Desc2 instances because
# non-data descriptors are shadowed by instance attributes.
# - The behavior for z is also subtle because dataclasses access the
# descriptor during default extraction.
#
# These cases are therefore omitted from the conformance suite until the
# expected behavior is specified more clearly.