]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-43558: Add note about base class initialization to dataclasses doc (GH-25967...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Mon, 10 May 2021 13:38:46 +0000 (06:38 -0700)
committerGitHub <noreply@github.com>
Mon, 10 May 2021 13:38:46 +0000 (09:38 -0400)
(cherry picked from commit 2a031723eefcf6f1d678bbb4f6018610d43623c4)

Co-authored-by: dhoekstra2000 <douwe.hoekstra2512@gmail.com>
Co-authored-by: dhoekstra2000 <douwe.hoekstra2512@gmail.com>
Doc/library/dataclasses.rst
Misc/ACKS
Misc/NEWS.d/next/Documentation/2021-05-07-12-27-09.bpo-43558.UGhA8R.rst [new file with mode: 0644]

index bfba15e96dce28fcf01eaa8a6b51d6d42b63c46d..e203a1a2132df90e61a2f4e793951e63fb9dad80 100644 (file)
@@ -491,6 +491,27 @@ depend on one or more other fields.  For example::
         def __post_init__(self):
             self.c = self.a + self.b
 
+The :meth:`__init__` method generated by :func:`dataclass` does not call base
+class :meth:`__init__` methods. If the base class has an :meth:`__init__` method
+that has to be called, it is common to call this method in a
+:meth:`__post_init__` method::
+
+    @dataclass
+    class Rectangle:
+        height: float
+        width: float
+
+    @dataclass
+    class Square(Rectangle):
+        side: float
+
+        def __post_init__(self):
+            super().__init__(self.side, self.side)
+
+Note, however, that in general the dataclass-generated :meth:`__init__` methods
+don't need to be called, since the derived dataclass will take care of
+initializing all fields of any base class that is a dataclass itself.
+
 See the section below on init-only variables for ways to pass
 parameters to :meth:`__post_init__`.  Also see the warning about how
 :func:`replace` handles ``init=False`` fields.
index 480a486a24c0b04646c1a391b91e7fee76092e01..b023bcb6d72fd367cbcfdaa3f957d2eb26654db7 100644 (file)
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -736,6 +736,7 @@ David Hobley
 Tim Hochberg
 Benjamin Hodgson
 Joerg-Cyril Hoehle
+Douwe Hoekstra
 Gregor Hoffleit
 Chris Hoffman
 Tim Hoffmann
diff --git a/Misc/NEWS.d/next/Documentation/2021-05-07-12-27-09.bpo-43558.UGhA8R.rst b/Misc/NEWS.d/next/Documentation/2021-05-07-12-27-09.bpo-43558.UGhA8R.rst
new file mode 100644 (file)
index 0000000..b0ecb17
--- /dev/null
@@ -0,0 +1,2 @@
+Add the remark to :mod:`dataclasses` documentation that the :meth:`__init__` of any base class\r
+has to be called in :meth:`__post_init__`, along with a code example.
\ No newline at end of file