Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,11 @@ def _get_field(cls, a_name, a_type, default_kw_only):
# If the default value isn't derived from Field, then it's only a
# normal default value. Convert it to a Field().
default = getattr(cls, a_name, MISSING)
# First checks if default is a descriptor,
# then checks if there is no default value returned by default.__get__.
if hasattr(default, "__get__") and default is cls.__dict__.get(a_name):
default = MISSING

if isinstance(default, Field):
f = default
else:
Expand Down
17 changes: 17 additions & 0 deletions Lib/test/test_dataclasses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4186,6 +4186,23 @@ class C:
with self.assertRaisesRegex(TypeError, 'missing 1 required positional argument'):
c = C()

def test_return_self_no_default_value(self):
class D:
def __get__(self, instance: Any, owner: object) -> Any:
if instance is None:
return self
return instance._x

def __set__(self, instance: Any, value: int) -> None:
instance._x = value

@dataclass
class C:
i: D = D()

with self.assertRaisesRegex(TypeError, 'missing 1 required positional argument'):
c = C()

class TestStringAnnotations(unittest.TestCase):
def test_classvar(self):
# Some expressions recognized as ClassVar really aren't. But
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Previously descriptors that return themselves from calls to ``__get__`` were
treated as default values in a dataclass. Now, a ``TypeError`` is raised if no
initial value is provided to the dataclass constructor.

Loading