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

Terry Jan Reedy tjreedy at udel.edu
Tue Apr 9 04:15:14 CEST 2013


On 4/8/2013 9:54 PM, Zahari Petkov wrote:
> Hello again,
>
> Unfortunatelly, the idea cannot be expressed in the simplest way, since this
> leads to confusion, so I present three short gists and explain the case in this
> email with a bit more words. I am writing it, since I am confident at least it
> will be an interesting read.
>
> All of the three gists present a different implementation of a simple case
> with 4 very simple classes involved.
>
> There are two classes which render instances of types `int` and `float`
> (IntRenderer and FloatRenderer). Imagine similar classes that may render
> any other given type - user classes, a list, etc., but for simplification
> of the case I use only two classes. Each of those classes is instantiated with
> a variable and is called to render this variable into a string.
>
> There is an abstract base class (Renderer), which provides the common
> implementation for all the descendants and leaves the `__call__` to the be
> implemented by the concrete classes.
>
> The last, fourth, class is a dispatcher, which has the sole purpose to pick
> the right renderer, call it and return the result. We prefer many specialized
> classes instead of one big class that may render all types.
>
> The first gist uses composition to achieve that, which would be the
> usual way to do that. The dispatcher iterates, picks the right renderer, calls
> it and returns the value:
>
> https://gist.github.com/majorz/5342257
>
> Cooperative inheritance is however also a great pick for such a use case. In
> this type of implementation if a subclass cannot do the job (render), it will
> delegate the work with super() to the next class in the mro chain.

If you inherit from 20 or 100 classes, each attribute access becomes a 
substantial linear search. I would forget inheritance and use a dict 
mapping class of the object being rendered to the data needed to render 
it. In your simple case, the dict would be {int:'INTEGER {}', 
float:'FLOAT {}'}.

  The usage
> of `__private` is justified here, since each subclass in the chain has to
> ensure that some of the used methods are his own internal methods:
>
> https://gist.github.com/majorz/5342262
>
> And here in this second gist we can immediately spot that the __call__ method
> has exactly the same textual representation (although the bytecode and the
> runtime environment are different). If we have hundred such classes, then we
> have to copy/paste this code hundred times, which is not good. (here I define
> the problem trying to solve).

These two sentences suggest to me that this is the wrong approach.

--
Terry Jan Reedy






More information about the Python-ideas mailing list