Skip to content

Commit b132be8

Browse files
miss-islingtonhbq1
andauthored
bpo-43176: Fix processing of empty dataclasses (GH-24484)
When a dataclass inherits from an empty base, all immutability checks are omitted. This PR fixes this and adds tests for it. Automerge-Triggered-By: GH:ericvsmith (cherry picked from commit 376ffc6) Co-authored-by: Iurii Kemaev <[email protected]>
1 parent bdee2a3 commit b132be8

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

Lib/dataclasses.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -834,7 +834,7 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
834834
# Only process classes that have been processed by our
835835
# decorator. That is, they have a _FIELDS attribute.
836836
base_fields = getattr(b, _FIELDS, None)
837-
if base_fields:
837+
if base_fields is not None:
838838
has_dataclass_bases = True
839839
for f in base_fields.values():
840840
fields[f.name] = f

Lib/test/test_dataclasses.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2568,6 +2568,30 @@ class D(C):
25682568
self.assertEqual(d.i, 0)
25692569
self.assertEqual(d.j, 10)
25702570

2571+
def test_inherit_nonfrozen_from_empty_frozen(self):
2572+
@dataclass(frozen=True)
2573+
class C:
2574+
pass
2575+
2576+
with self.assertRaisesRegex(TypeError,
2577+
'cannot inherit non-frozen dataclass from a frozen one'):
2578+
@dataclass
2579+
class D(C):
2580+
j: int
2581+
2582+
def test_inherit_nonfrozen_from_empty(self):
2583+
@dataclass
2584+
class C:
2585+
pass
2586+
2587+
@dataclass
2588+
class D(C):
2589+
j: int
2590+
2591+
d = D(3)
2592+
self.assertEqual(d.j, 3)
2593+
self.assertIsInstance(d, C)
2594+
25712595
# Test both ways: with an intermediate normal (non-dataclass)
25722596
# class and without an intermediate class.
25732597
def test_inherit_nonfrozen_from_frozen(self):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed processing of empty dataclasses.

0 commit comments

Comments
 (0)