[Python-ideas] Name mangling and code repetition (with cooperative inheritance use case)
Zahari Petkov
zarchaoz at gmail.com
Tue Apr 9 01:11:18 CEST 2013
Hello everyone,
In a certain implementation where I was doing some form of dispatch using
composition, I decided to try out cooperative inheritance with super. However,
I stumbled at something unexpected - there was nothing wrong with cooperative
inheritance with super, but the implementation started to have repetative
code, which could not be easily resolved, because of how name mangling of
private attribute works.
In short my proposal is for a language feature or mechanism, which will allow
automatic redefinition of methods through the descendants of a superclass
during compilation time - at the same time name unmangling is done. In the
example below I use a decorator - just to illustrate the idea in a very simple
way:
class A:
__val = 'a'
@propagate_through_descendants
def print_val(self):
print(self.__val)
class B(A):
__val = 'b'
b = B()
b.print_val()
Please, check the following gist for a bit more concrete example (short and
working) with cooperative inheritance:
https://gist.github.com/majorz/5341333
The code duplication is very obvious and unavoidable (the two __call__
methods have exactly the same code, which cannot be moved to the superclass).
I tried some metaprogramming, but even then it was hard to resolve, since
name unmangling seems to happen during complilation time as far as I
understand.
Thanks,
Zahari
More information about the Python-ideas
mailing list