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):
print 'descriptor.__get__ self=%r instance=%r owner=%r' % (
self, instance, owner)
return self
def __set__(self, instance, value):
# I want to know the *name* this value is being assigned to
print 'descriptor.__set__ self=%r instance=%r value=%r' % (
self, instance, value)
def __delete__(self, instance):
print 'descriptor.__delete__ self=%r instance=%r' % (
self, instance)
class X(object):
foo = descriptor()
x = X()
x.foo = "value"
I can obtain the name descriptor() was assigned to at the time the X class
was defined, using a custom metaclass:
class Meta(type):
def __new__(meta, name, bases, dict):
for key,value in dict.iteritems():
if isinstance(value, descriptor):
value.name = key
return type.__new__(meta, name, bases, dict)
class Y(object):
__metaclass__ = Meta
foo = descriptor()
y = Y()
print y.foo.name # prints 'foo'
This is good enough for me (assuming no one modifies the class after
defining it, no two names refer to the same descriptor, no two classes
share the same descriptor instance...). But I would like to use a more
direct/robust approach, if available.
Any ideas?
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list