[Python-ideas] Name mangling and code repetition (with cooperative inheritance use case)

Guido van Rossum guido at python.org
Tue Apr 9 01:15:04 CEST 2013


You are misunderstanding __private. It is for use *within one class*
only. For your purpose you should use single underscore (sometimes
known as "protected").

On Mon, Apr 8, 2013 at 4:11 PM, Zahari Petkov <zarchaoz at gmail.com> wrote:
> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas



-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list