Skip to content
Closed
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
12 changes: 12 additions & 0 deletions Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,18 @@ def _frozen_get_del_attr(cls, fields):
' raise FrozenInstanceError(f"cannot delete field {name!r}")',
f'super(cls, self).__delattr__(name)'),
globals=globals),
_create_fn('__getstate__',
('self',),
('fields = getattr(self, _fields)',
'valid_fields = tuple(f.name for f in fields.values() if f._field_type is _FIELD)',
'return [(attr, getattr(self, attr, None)) for attr in valid_fields]',
),
globals=dict(globals, _fields=_FIELDS, _FIELD=_FIELD)),
_create_fn('__setstate__',
('self', 'state'),
('for slot, value in state:',
' object.__setattr__(self, slot, value)'),
globals=globals),
)


Expand Down
16 changes: 16 additions & 0 deletions Lib/test/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1914,6 +1914,22 @@ class R:
self.assertEqual(new_sample.x, another_new_sample.x)
self.assertEqual(sample.y, another_new_sample.y)

def test_frozen_dataclasses_pickleable(self):
global S
@dataclass(frozen=True)
class S:
__slots__ = ('x', 'y')
x: int
y: int

sample = S(42, 24)
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(sample=sample, proto=proto):
new_sample = pickle.loads(pickle.dumps(sample, proto))
self.assertEqual(sample.x, new_sample.x)
self.assertEqual(sample.y, new_sample.y)
self.assertIsNot(sample, new_sample)


class TestFieldNoAnnotation(unittest.TestCase):
def test_field_without_annotation(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Frozen dataclasses, in conjunction with with __slots__, cannot be unpickled,
as we were using `__setattr__` to set the new instance's attribute which
conflicts with the __slots__ definition. Adding `__getstate__` and
`__setstate__` for these classes should alleviate the issue, as we can use
`object.__setattr__` instead to set the frozen attributes on instance's
state assignment.