Multiple inheritance, super() and changing signature

Ben Finney ben+python at benfinney.id.au
Fri Jun 3 20:44:09 EDT 2016


Ian Kelly <ian.g.kelly at gmail.com> writes:

> Except that since we're discussing design for multiple inheritance,
> the positional argument "spam" is inappropriate. All arguments should
> be passed by keyword; the DolorSitAmet.__init__ method cannot be
> certain that LoremIpsum will be the next class in the MRO, and the
> actual next class might not expect spam to be the first positional
> argument.

You're right. That also allows us to stop handling unknown positional
arguments.

This does make it troublesome to design the function signature though,
and I can see why people balk at how to deal with the semantics of
‘super’ in Python 2::

    class LoremIpsum(object):
        def __init__(self, **kwargs):
            spam = kwargs.pop('spam')
            do_something_important_with(spam)
            super(LoremIpsum, self).__init__(**kwargs)

    class DolorSitAmet(LoremIpsum):
        def __init__(self, **kwargs):
            self.eggs = kwargs.pop('eggs')
            self.beans = kwargs.pop('beans')
            super(DolorSitAmet, self).__init__(**kwargs)

That's awful :-( because the initialiser's signature no longer shows any
sign of which parameters matter for this class.

It also sucks to need ‘dict.pop('name')’, instead of just ‘name’.


Keyword-only parameters make this easier and clearer::

    class LoremIpsum:
        def __init__(self, *, spam, **kwargs):
            spam = kwargs.pop('spam')
            do_something_important_with(spam)
            super().__init__(**kwargs)

    class DolorSitAmet(LoremIpsum):
        def __init__(self, *, eggs=4, beans=None, **kwargs):
            self.eggs = eggs
            self.beans = beans
            super().__init__(**kwargs)

I guess that's yet another reason to advocate Python 3 for all new code.

-- 
 \          “One time a cop pulled me over for running a stop sign. He |
  `\        said, ‘Didn't you see the stop sign?’ I said, ‘Yeah, but I |
_o__)                don't believe everything I read.’” —Steven Wright |
Ben Finney




More information about the Python-list mailing list