|
2 | 2 | Tests the handling of descriptors within a dataclass. |
3 | 3 | """ |
4 | 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. |
| 5 | +# A data descriptor used as a dataclass field is handled according to the |
| 6 | +# runtime implementation: the field type is the type returned by ``__get__``. |
| 7 | +# |
| 8 | +# The behavior of non-data descriptors (descriptors with only ``__get__``) used |
| 9 | +# as dataclass fields is under-specified and type checkers disagree, so those |
| 10 | +# cases are intentionally omitted here. See |
| 11 | +# https://github.com/python/typing/issues/2259. |
7 | 12 |
|
8 | 13 | from dataclasses import dataclass |
9 | | -from typing import Any, Generic, TypeVar, assert_type, overload |
10 | | - |
11 | | -T = TypeVar("T") |
| 14 | +from typing import Any, assert_type, overload |
12 | 15 |
|
13 | 16 |
|
14 | 17 | class Desc1: |
@@ -36,33 +39,3 @@ class DC1: |
36 | 39 |
|
37 | 40 | assert_type(dc1.y, int) |
38 | 41 | 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) |
67 | | -assert_type(dc2.y, str) |
68 | | -assert_type(dc2.z, str) |
0 commit comments