class super method
george.sakkis at gmail.com
Tue Apr 1 18:48:26 CEST 2008
On Apr 1, 10:21 am, Ed Leafe <e... at leafe.com> wrote:
> On Apr 1, 2008, at 8:43 AM, George Sakkis wrote:
> > Pehaps, at least as long as you make sure that all superclasses have a
> > compatible signature - which in practice typically means accept
> > arbitrary *args and **kwargs in every class in the hierarchy like your
> > example. Good luck figuring out what's wrong if it's not used
> > consistently.
> See my comment above. If you do not know what you're doing, you
> shouldn't be doing it. This is not the fault of super(); it's the
> fault of a poor programmer. And I used generic *args and **kwargs in
> the method sig since I was using made-up class names and methods.
> Would you have reacted more favorably if I had used (self, foo, bar)
No, that was exactly my point; with a non-generic signature like
(self, foo, bar), it's a matter of time until some subclass breaks it.
Non-trivial hierarchies with all __init__ having compatible signatures
is not typical in my experience, but they have to be compatible to be
used correctly with super. Here is the conclusion from the second
article I linked:
If you do use super, here are some best practices:
* Use it consistently, and document that you use it, as it is part
of the external interface for your class, like it or not.
* Never call super with anything but the exact arguments you
received, unless you really know what you're doing.
* When you use it on methods whose acceptable arguments can be
altered on a subclass via addition of more optional arguments, always
accept *args, **kw, and call super like "super(MyClass,
self).currentmethod(alltheargsideclared, *args, **kwargs)". If you
don't do this, forbid addition of optional arguments in subclasses.
* Never use positional arguments in __init__ or __new__. Always
use keyword args, and always call them as keywords, and always pass
all keywords on to super.
> > In a sentence, it's better than nothing but worse than anything.
> I guess I must be the world's most amazing Python developer, as I've
> used super() extensively for years without ever suffering any of the
> pitfalls you and others describe.
Some people use the same argument for explicit memory management in C/C
++. Sure, it can be done, but that doesn't make it elegant or trivial.
When experts like Michele Simionato find super() tricky enough to
write an article about it, that says something.
More information about the Python-list