[Python-Dev] Python interface to attribute descriptors

Phillip J. Eby pje@telecommunity.com
Thu, 14 Nov 2002 12:53:00 -0500


To answer your question about getting attribute names, take a look at:

http://cvs.eby-sarna.com/PEAK/src/peak/binding/once.py?rev=1.22&content-type=text/vnd.viewcvs-markup

It's a working example of a use of a metaclass (ActiveDescriptors) that 
will "activate" descriptors added to it, and tell them their names.

You'll note that the descriptor objects make copies of themselves when 
activated, if the name given to them differs from the name they "guessed" 
when they were created.  This is so that descriptors can be safely shared 
and reused in multiple classes (or even the same one) under different names.

peak.binding.once is of course just a small part of the PEAK system, but if 
you want to use the code, you can.  You'll need to strip out some of the 
PEAK specifics like IBindingFactory, EigenRegistry, and importObject, 
though.  Really, probably all you need for what you're doing is this part:

class ActiveDescriptors(type):

     """Type which gives its descriptors a chance to find out their names"""

     def __init__(klass, name, bases, dict):

         for k,v in dict.items():
             if isinstance(v,ActiveDescriptor):
                 v.activate(klass,k)

         super(ActiveDescriptors,klass).__init__(name,bases,dict)


class ActiveDescriptor(object):

     """This is just a (simpler sort of) interface assertion class"""

     def activate(self,klass,attrName):
         """Informs the descriptor that it is in 'klass' with name 
'attrName'"""
         raise NotImplementedError


and then define a base class which has ActiveDescriptors as its metaclass, 
and use it for all your classes that will use ActiveDescriptor-subclass 
instances.