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

Nick Coghlan ncoghlan at gmail.com
Tue Apr 9 07:43:11 CEST 2013


On Tue, Apr 9, 2013 at 2:24 PM, Zahari Petkov <zarchaoz at gmail.com> wrote:
> You give me here some very nice ideas, which I am going to explore
> more tomorrow, including trying out ChainMap. Thanks for working on
> this and suggesting those.
>
> Back on the original topic, as I understand from the Guido's answers
> the `__private` attributes have a very specific purpose (e.g. the one
> explained in the tutorial) and it is not intended as a generic tool
> like other language features are. Although my code is working
> correctly, since I am going outside of the indented boundaries, it is
> normal to hit some rough corners. That invalidates my original idea
> about eliminating the duplicated code case, since it is a result of
> wrong presumption - that '__private' attributes is a generic tool.
> Probably no need to continue further with the `__private` discussion.
> It is anyway with little practical use.

If you would like to use the MRO of the subclass to walk a priority
list in a specific order, just do that, instead of trying to use
super() to do it recursively.

The base class implementation might look something like:

    class Render:
        def __init__(self, entity):
            self._entity = entity
            for cls in self.__class__.mro():
                if isinstance(self._entity, cls._render_type):
                    self._render_entity = cls._render
                    break
            else:
                raise TypeError("Cannot render %r instance" % type(entity))

    def __call__(self):
        self._render_entity(self)

You could combine something like this with a more conventional system
that accepted a list of renderers.

This all still sounds more complicated than seems wise, but iterating
over the MRO explicitly is a useful alternative once you start hitting
the limits of super().

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list