Detect target name in descriptor __set__ method
Rainer Mansfeld
MLists at romulo.de
Thu Jul 23 10:44:56 EDT 2009
Gabriel Genellina schrieb:
> 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 descriptor(object):
def __get__(self, instance, owner):
return self
def __set__(self, instance, value):
# I want to know the *name* this value is being assigned to
for name in instance.__class__.__dict__:
if getattr(instance, name) is self:
print "assigning to %s" % name
break
class X(object):
foo = descriptor()
bar = descriptor()
class Y(object):
foo = descriptor()
baz = descriptor()
x = X()
y = Y()
x.foo = "value"
x.bar = "value"
y.foo = "value"
y.baz = "value"
Does this work for you?
Rainer
More information about the Python-list
mailing list