Skip to content

Commit 5d16973

Browse files
committed
default value check for descriptors
1 parent e779777 commit 5d16973

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

Lib/dataclasses.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -831,6 +831,11 @@ def _get_field(cls, a_name, a_type, default_kw_only):
831831
# If the default value isn't derived from Field, then it's only a
832832
# normal default value. Convert it to a Field().
833833
default = getattr(cls, a_name, MISSING)
834+
# First checks if default is a descriptor,
835+
# then checks if there is no default value returned by default.__get__.
836+
if hasattr(default, "__get__") and default is cls.__dict__.get(a_name):
837+
default = MISSING
838+
834839
if isinstance(default, Field):
835840
f = default
836841
else:

Lib/test/test_dataclasses/__init__.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4186,6 +4186,23 @@ class C:
41864186
with self.assertRaisesRegex(TypeError, 'missing 1 required positional argument'):
41874187
c = C()
41884188

4189+
def test_return_self_no_default_value(self):
4190+
class D:
4191+
def __get__(self, instance: Any, owner: object) -> Any:
4192+
if instance is None:
4193+
return self
4194+
return instance._x
4195+
4196+
def __set__(self, instance: Any, value: int) -> None:
4197+
instance._x = value
4198+
4199+
@dataclass
4200+
class C:
4201+
i: D = D()
4202+
4203+
with self.assertRaisesRegex(TypeError, 'missing 1 required positional argument'):
4204+
c = C()
4205+
41894206
class TestStringAnnotations(unittest.TestCase):
41904207
def test_classvar(self):
41914208
# Some expressions recognized as ClassVar really aren't. But

0 commit comments

Comments
 (0)