is decorator the right thing to use?

Aaron "Castironpi" Brady castironpi at gmail.com
Fri Sep 26 13:54:10 EDT 2008


On Sep 26, 10:41 am, "Dmitry S. Makovey" <dmi... at athabascau.ca> wrote:
> Paul McGuire wrote:
> > If you need to get fancier and support this single-proxy-to-multiple-
> > delegates form, then yes, you will need some kind of map that says
> > which method should delegate to which object.  Or, if it is just a
> > matter of precedence (try A, then try B, then...), then use hasattr to
> > see if the first delegate has the given attribute, and if not, move on
> > to the next.
>
> that is what I didn't like about it - I have to iterate over delegates when
> I can build direct mapping once and for all and tie it to class
> definition ;)

You're right, there is a difference in performance.  But it would
still be simpler to have your 'getattr' method 'learn' what functions
come from what objects, and then just route directly to them.

> __getattr__ implies constant lookups and checks (for filtering purposes) - I
> want to do them once, attach generated methods as native methods and be
> done with it. That is why I do not like __getattr__ in this particular
> case. Otherwise - you're right.

Try this (untested!):

def __getattr__( self, key ):
    if key in self.knownmeths:
        return self.knownmeths[ key ]
    for x in self.delegs:
        if hasattr( x, key ):
            _= self.knownmethds[ key ]= getattr( x, key )
            return _
    raise name not found

self.knownmethds has desired order of precedence.



More information about the Python-list mailing list