Are there good (suitable for using in real projects) ways or reducing boilerplate in things like this
class B(A):
def qqq(self): # 1 unwanted token "self"
super(B, self).qqq() # 7 unwanted tokens plus 2 duplications ("B", "qqq")
do_something()
I want it to look more like this:
class B(A):
def qqq:
super
do_something()
or (more realistically)
class B(A):
@autosuper_before
def qqq(self):
do_something()
Is it possible in Python 2.6+ without overt hacks?
tl;dr
As the OP said “Is it possible in Python 2.6+ without overt hacks?”, the answer is: No
Long version
You can make a simple decorator that will call the next parent with this method. The problem is that you will not have control on the arguments you want to pass.Edit:
This will not work for a subclass already using
autosuperbecause it’ll chose the wrong class and make an infinite loop.How could this be done? Python 3.x do have a
superfunction that takes no arguments!Unfortunally, the Python 3.x’s
superis a class and at the same time a keyword, because just the presence of its name will change the current environment to unveil a variable named__class__that is the right class you need to use!If you check the frame inside a function declared in a class, there’s no
__class__variable and theco_freevarsattribute of the frame’sf_codeattribute is empty. When you write the namesuper(do not need to call it), the__class__string will appear inco_freevarsmeaning it comes from another closure. Also, if you try to access the__class__variable without using super, it’ll use theLOAD_DEFERbytecode for this same reason instead ofLOAD_GLOBALlike would be normal to every undefined name.This is so crazy that you cannot just do
hyper = superand call this newhypervariable without arguments (that is exactly the same object assuper).As I cannot compete with this much of black magic inside the Python Interpreter, and because the
autosuperdecorator is not declared inside a class (so it can never access the__class__variable even if that was possible in Python 2.x), I will not try to write a new decorator and will leave this answer here as a warn for other people who want to do that.It is probably possible to make some hackeries to find the right class to use, but I will not dig that far. Things to consider:
unbound method(that were removed anyway from Py3k) so you cannot check theim_classattribute.__class__variable do exist and it is possible to get a reference to it)