]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-43176: Fix processing of empty dataclasses (GH-24484)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Tue, 6 Apr 2021 05:31:54 +0000 (22:31 -0700)
committerGitHub <noreply@github.com>
Tue, 6 Apr 2021 05:31:54 +0000 (22:31 -0700)
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 376ffc6ac491da74920aed1b8e35bc371cb766ac)

Co-authored-by: Iurii Kemaev <6885137+hbq1@users.noreply.github.com>
Lib/dataclasses.py
Lib/test/test_dataclasses.py
Misc/NEWS.d/next/Library/2021-02-09-07-24-29.bpo-43176.bocNQn.rst [new file with mode: 0644]

index c38e16a2d94c7cf5722ae147424c88e80b3003c3..5825e8e52305380efc4a30803ab9e065dde20c83 100644 (file)
@@ -834,7 +834,7 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
         # Only process classes that have been processed by our
         # decorator.  That is, they have a _FIELDS attribute.
         base_fields = getattr(b, _FIELDS, None)
-        if base_fields:
+        if base_fields is not None:
             has_dataclass_bases = True
             for f in base_fields.values():
                 fields[f.name] = f
index bbcf30c983d3a1e547803f242bf1976c740d5868..548f10b7cafb99fbe6add0edd82339c0b75ff13a 100755 (executable)
@@ -2568,6 +2568,30 @@ class TestFrozen(unittest.TestCase):
         self.assertEqual(d.i, 0)
         self.assertEqual(d.j, 10)
 
+    def test_inherit_nonfrozen_from_empty_frozen(self):
+        @dataclass(frozen=True)
+        class C:
+            pass
+
+        with self.assertRaisesRegex(TypeError,
+                                    'cannot inherit non-frozen dataclass from a frozen one'):
+            @dataclass
+            class D(C):
+                j: int
+
+    def test_inherit_nonfrozen_from_empty(self):
+        @dataclass
+        class C:
+            pass
+
+        @dataclass
+        class D(C):
+            j: int
+
+        d = D(3)
+        self.assertEqual(d.j, 3)
+        self.assertIsInstance(d, C)
+
     # Test both ways: with an intermediate normal (non-dataclass)
     #  class and without an intermediate class.
     def test_inherit_nonfrozen_from_frozen(self):
diff --git a/Misc/NEWS.d/next/Library/2021-02-09-07-24-29.bpo-43176.bocNQn.rst b/Misc/NEWS.d/next/Library/2021-02-09-07-24-29.bpo-43176.bocNQn.rst
new file mode 100644 (file)
index 0000000..66a175d
--- /dev/null
@@ -0,0 +1 @@
+Fixed processing of empty dataclasses.
\ No newline at end of file