← 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"""
2Tests 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
8from dataclasses import dataclass
9from typing import Any, Generic, TypeVar, assert_type, overload
11T = TypeVar("T")
14class Desc1:
15 @overload
16 def __get__(self, __obj: None, __owner: Any) -> "Desc1":
17 ...
19 @overload
20 def __get__(self, __obj: object, __owner: Any) -> int:
21 ...
23 def __get__(self, __obj: object | None, __owner: Any) -> "int | Desc1":
24 raise NotImplementedError
26 def __set__(self, __obj: object, __value: int) -> None:
27 ...
30@dataclass
31class DC1:
32 y: Desc1 = Desc1()
35dc1 = DC1(3)
37assert_type(dc1.y, int)
38assert_type(DC1.y, Desc1)
41class Desc2(Generic[T]):
42 @overload
43 def __get__(self, instance: None, owner: Any) -> list[T]:
44 ...
46 @overload
47 def __get__(self, instance: object, owner: Any) -> T:
48 ...
50 def __get__(self, instance: object | None, owner: Any) -> list[T] | T:
51 raise NotImplementedError
54@dataclass
55class DC2:
56 x: Desc2[int]
57 y: Desc2[str]
58 z: Desc2[str] = Desc2()
61assert_type(DC2.x, list[int])
62assert_type(DC2.y, list[str])
63assert_type(DC2.z, list[str])
65dc2 = DC2(Desc2(), Desc2(), Desc2())
66assert_type(dc2.x, int)
Unexpected error [type-assertion-failure] Type `int` does not match asserted type `int | Desc2[int]`
67assert_type(dc2.y, str)
Unexpected error [type-assertion-failure] Type `str` does not match asserted type `str | Desc2[str]`
68assert_type(dc2.z, str)