proxy class and __add__ method

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Jul 30 20:47:06 EDT 2008


En Wed, 30 Jul 2008 07:48:45 -0300, Magnus Schuster  
<magnusschuster at yahoo.com> escribi�:

>> __magic__ methods on new style classes are searched in the class, *not*  
>> in
>> the instance. prx_i+1 looks for __add__ in type(prx_i), that is, in the
>> proxy class.
>
> With this explanation the behaviour is absolutely clear. Can I find some
> documentation anywhere containing more background information how magic
> functions are resolved? I haven't been successful with the Python  
> Language
> Reference.

There is some documentation collected in  
http://www.python.org/doc/newstyle/ and you can see also PEP252 and  
PEP253...

>> Try implementing a similar __getattr__ method in a metaclass.
>
> I am totally clueless how to do this. Below you find my attempt. Neither
> __getattr__ nor __add__ of the metaclass 'meta' are ever called. May I  
> ask
> you for some more guidance or corrections to the code below?

Unfortunately, as you have noted, my suggestion of using a metaclass with  
__getattr__ doesn't work. That method isn't invoked when resolving those  
names.
I've found this recipe http://code.activestate.com/recipes/252151/ which  
goes step by step: first a Proxy for old-style classes that works fine,  
then a version for new-style classes identical to yours, then a metaclass  
version with __getattr__ that doesn't work either, and finally a working  
version. Very nice example.
Another -more complete- version is at  
http://code.activestate.com/recipes/496741/
I hope you can adapt these to match your requirements.

-- 
Gabriel Genellina




More information about the Python-list mailing list