Should one always add super().__init__() to the __init__?

Ian Kelly ian.g.kelly at gmail.com
Sun Sep 30 03:13:16 EDT 2012


On Sat, Sep 29, 2012 at 10:37 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> [1] You *should* call super, unless you have an excellent reason not to,
> so that your class doesn't break multiple-inheritance. But you need to do
> so with care making sure that the argument signatures are designed for
> cooperative use of super.

I disagree.  Most classes will not ever be used for multiple
inheritance, and the changes involved in "making sure that the
argument signatures are designed for cooperative use of super" are not
trivial.  For one, it means not being able to use positional arguments
in __init__ methods.  For two, the
receive-and-strip-off-keyword-arguments approach falls apart if you
have unrelated classes that take the same arguments.  For
illustration, suppose you have the following two classes, both of
which use a required Frobnik object to perform their functions.


class A:
    def __init__(self, frobnik, **kwargs):
        super().__init__(**kwargs)
        self._frobnik = frobnik
    ...

class B:
    def __init__(self, frobnik, **kwargs):
        super().__init__(**kwargs)
        self._frobnik = frobnik
    ...

Even though these classes have been designed to be cooperative, they
cannot be inherited together.  Whichever class is first in the MRO
will receive the frobnik argument and strip it off, and then the other
class's __init__ method will complain of a missing required argument.

There are solutions to this.  For instance, you could make frobnik
optional in each class, each one relying on the other to receive the
frobnik argument if it is missing, but this complicates the
implementations and makes it difficult to detect in a timely manner if
the frobnik argument has actually not been supplied.  Or you could
change the name of the argument in one of the classes, but then your
library users will complain of inconsistent naming.

What it boils down to is that classes that are expected to be used for
multiple inheritance should be designed to use super cooperatively,
but the majority of classes that you write should not have to deal
with these sorts of restrictions.  Classes that will only ever be
singly inherited should be written normally and using whatever
superclass call style feels most appropriate.



More information about the Python-list mailing list