Detect target name in descriptor __set__ method

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Jul 22 19:52:06 EDT 2009


En Wed, 22 Jul 2009 05:31:13 -0300, Jon Clements <joncle at googlemail.com>  
escribió:
> On 22 July, 06:02, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:

>> I have a class attribute 'foo' which is a data descriptor. I create an  
>> instance of such class. When I say instance.foo = value, the descriptor  
>>  
>> __set__ method is called. Is there any way to obtain the name being  
>> assigned to? ('foo' in this example). That is, I want to know the  
>> target  
>> name for the assignment that triggered the __set__ method call.

>>>> class Test:
> 	def __setattr__(self, what, value):
> 		print what, value
>
>
>>>> t = Test()
>>>> t.foo = 'x'
> foo x
>
> Is that what you're after?

Yes and no. __setattr__ has a terrible overhead as it is invoked for each  
and every attribute being set, special or not. Using a custom descriptor  
seems better, because it allows to intercept just the desired attribute.  
If only I had access to the name being used...

-- 
Gabriel Genellina




More information about the Python-list mailing list