Skip to content

Commit f47305a

Browse files
bpo-43558: Add note about base class initialization to dataclasses doc (GH-25967) (GH-26018)
(cherry picked from commit 2a03172) Co-authored-by: dhoekstra2000 <[email protected]> Co-authored-by: dhoekstra2000 <[email protected]>
1 parent 9a0e65c commit f47305a

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

Doc/library/dataclasses.rst

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,27 @@ depend on one or more other fields. For example::
491491
def __post_init__(self):
492492
self.c = self.a + self.b
493493

494+
The :meth:`__init__` method generated by :func:`dataclass` does not call base
495+
class :meth:`__init__` methods. If the base class has an :meth:`__init__` method
496+
that has to be called, it is common to call this method in a
497+
:meth:`__post_init__` method::
498+
499+
@dataclass
500+
class Rectangle:
501+
height: float
502+
width: float
503+
504+
@dataclass
505+
class Square(Rectangle):
506+
side: float
507+
508+
def __post_init__(self):
509+
super().__init__(self.side, self.side)
510+
511+
Note, however, that in general the dataclass-generated :meth:`__init__` methods
512+
don't need to be called, since the derived dataclass will take care of
513+
initializing all fields of any base class that is a dataclass itself.
514+
494515
See the section below on init-only variables for ways to pass
495516
parameters to :meth:`__post_init__`. Also see the warning about how
496517
:func:`replace` handles ``init=False`` fields.

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -736,6 +736,7 @@ David Hobley
736736
Tim Hochberg
737737
Benjamin Hodgson
738738
Joerg-Cyril Hoehle
739+
Douwe Hoekstra
739740
Gregor Hoffleit
740741
Chris Hoffman
741742
Tim Hoffmann
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Add the remark to :mod:`dataclasses` documentation that the :meth:`__init__` of any base class
2+
has to be called in :meth:`__post_init__`, along with a code example.

0 commit comments

Comments
 (0)