is decorator the right thing to use?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Fri Sep 26 16:03:39 EDT 2008


Dmitry S. Makovey a écrit :
> Paul McGuire wrote:
>>> see, in your code you're assuming that there's only 1 property ( 'b' )
>>> inside of A that needs proxying. In reality I have several. 
> <snip/>
>> No, really, Diez has posted the canonical Proxy form in Python, using
>> __getattr__ on the proxy, and then redirecting to the contained
>> delegate object.  This code does *not* assume that only one property
>> ('b'? where did that come from?) is being redirected - __getattr__
>> will intercept all attribute lookups and redirect them to the
>> delegate.
>>
>> 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 ;) 

Hem... I'm afraid you don't really take Python's dynamic nature into 
account here. Do you know that even the __class__ attribute of an 
instance can be rebound at runtime ? What about 'once and for all' then ?

But anyway:

>> Your original question was "is decorator the right thing to use?"  For
>> this application, the answer is "no".  
> 
> yeah. seems that way. in the other fork of this thread you'll find my
> conclusion which agrees with that :)
> 
>> It sounds like you are trying 
>> to force this particular to solution to your problem, but you are
>> probably better off giving __getattr__ intercepting another look.
> 
> __getattr__ implies constant lookups and checks (for filtering purposes)

Unless you cache the lookups results...

> - I
> want to do them once, attach generated methods as native methods

What is a "native method" ? You might not be aware of the fact that 
method objects are usually built anew from functions on each method call...

> and be
> done with it. That is why I do not like __getattr__ in this particular
> case. 

There's indeed an additional penalty using __getattr__, which is that 
it's only called as a last resort. Now remember that premature 
optimization is the root of evil... Depending on effective use (ie : how 
often a same 'proxied' method is called on a given Proxy instance, on 
average), using __getattr__ to retrieve the appropriate bound method on 
the delegate then adding it to the proxy instance *as an instance 
attribute* might be a way better (and simpler) optimization.



More information about the Python-list mailing list