Python's super() considered super!

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri May 27 06:37:13 EDT 2011


On Fri, 27 May 2011 18:49:52 +1000, Ben Finney wrote:

> Raymond Hettinger <python at rcn.com> writes:
> 
>> Hope you enjoyed the post.
> 
> I certainly did.
> 
> But I'm not better enlightened on why ‘super’ is a good thing. 

Perhaps Raymond assumed that by now everybody knows that multiple 
inheritance in Python that doesn't use super is buggy. super() was 
introduced in version 2.2 in order to overcome bugs in MI, making it 
about 8 years old now.

(Technically, it's only MI with diamond-shaped inheritance, but that 
applies to *all* new-style classes. If you're writing multiple 
inheritance in Python 3 without using super, your code is a land-mine 
waiting to go off. If you're writing single inheritance, it's *still* a 
land-mine, just waiting for some poor caller to use it in a MI context.)

But I do agree with you in that I expected to see at least some 
discussion of why super should be actively preferred over calling the 
parent class directly.


> The
> exquisite care that you describe programmers needing to maintain is IMO
> just as much a deterrent as the super-is-harmful essay.

I don't see that Raymond describes anything needing "exquisite care". 
It's more common sense really: ensure that your method signature and that 
of your parents' match, plus good work-arounds for when they don't. 
Anyone using inheritance is almost certainly 98% of the way there, unless 
they're writing classes like this and wondering why they don't work :)

class MyBrokenList(list):
    def __len__(self):
        n = list.__len__(self, extra=42)
        return n + 1
    def __getitem__(self, i):
        return list.__getitem__(self) + 1
    def last_item(self):
        return list.last_item(self) + 1


I was thrilled to learn a new trick, popping keyword arguments before 
calling super, and wondered why I hadn't thought of that myself. How on 
earth did I fail to realise that a kwarg dict was mutable and therefore 
you can remove keyword args, or inject new ones in?

Given the plethora of articles that take a dim, if not outright negative, 
view of super, it is good to see one that takes a positive view. Thanks 
Raymond!



-- 
Steven



More information about the Python-list mailing list