Saturday, 8 September 2018

When and how should I use super?

super is a very important function in python, but unfortunately it is very difficult to use correctly. Even if you understand what super does, using it correctly is still difficult. One example of proper super usage that isn't immediately obvious is to use only keyword (and no positional) arguments in a cooperative multiple inheritance scenario in order to guarantee the same behavior regardless of the order of the parent classes. It's easy to do something wrong when using super, which is why I think a comprehensive guide to using super would be extremely beneficial to have.

The question is simple:

When and how should super be used? When should it not be used?

Taking into account things like:

  • The number of parent classes: Does the use of super differ in single inheritance vs multiple inheritance?
  • The interface of the parent classes: Are the parent classes designed for cooperative inheritance? Is one parent class a mixin? Do the parent classes use super?
  • Forced inheritance: Since all classes are subclasses of object, should super be used differently in a class that inherits directly from object?

And any other considerations that may be relevant.

Note that the question "how should super be used?" does not refer to the 4 different ways to call super. Rather, it's a question of "Which arguments should be forwarded to the super call?".

  • Should a method take *args and/or **kwargs and forward them to the super call?
  • Should a method forward any other arguments?

I realize that this is a broad question. But as I've already said, I think there is a lot of merit in having a comprehensive guide for using super, because it is the cornerstone of inheritance in python. Please bear with me. Let's do the python community a service.



from When and how should I use super?

No comments:

Post a Comment