Late initialization using __getattribute__

Carl Banks pavlovevidence at
Thu Sep 4 21:19:28 CEST 2008

On Sep 4, 12:36 pm, bukzor <workithar... at> wrote:
> > >>> so unfortunately I think I need to use __getattribute__
> > >>> to do this. I'm doing all this just to make the connection not
> > >>> actually connect until used.
> > >> I may be dumb, but I don't get how this is supposed to solve your
> > >> problem. But anyway : there's a known design pattern for what you're
> > >> trying to do, that doesn't require mixins nor messing with
> > >> __getattribute__ (which, I repeat, is more often than not something you
> > >> *don't* want to do). The name of the design pattern is "proxy". I
> > >> strongly suggest that you 1/ try to cure the real problem instead of
> > >> hacking around and 2/ read about the proxy design pattern.
> > >> My 2 cents...
> > > I like the idea of mix-ins, but can't figure out how to make a proxy
> > > work that way.
> > You mean, "how to use a proxy for lazy initialization" ? Heck, that's
> > the exact use case in the GoF.
> I mean, "how to make a MixIn class that uses the proxy pattern".

You don't.  That's not how proxies work.

> I'd like to be able to do something like this:
> class SuperCursor(FeatureOneMixIn, FeatureTwoMixin, ...,
> VanillaCursor): pass

Why does it have to look like that?  A good programmer lets the code
look however it has to look to most effectively do it's job.

With a proxy, the "base class" isn't a base class but a member.  Here
is a very simple example:

class SuperCursor(object):
    def __init__(self):
        self._cursor = VanillaCursor()
        self._connected = False
    def __getattr__(self,attr):
        if not self._connected:
            self._connected = True
        return getattr(self._cursor,attr)

cursor = SuperCursor()

That doens't use a mixin, but why should it?

Carl Banks

More information about the Python-list mailing list