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

Joao S. O. Bueno jsbueno at python.org.br
Tue Apr 9 04:32:17 CEST 2013


On 8 April 2013 23:15, Terry Jan Reedy <tjreedy at udel.edu> wrote:
> 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 {}'}.

Which can easily be conbined with the "one render method per class"
writing style you (Zahari)  want with something just like:
https://gist.github.com/jsbueno/5342460



More information about the Python-ideas mailing list