properties + types, implementing meta-class desciptors elegantly?

Ian Bicking ianb at colorstudy.com
Fri Jul 18 17:42:14 EDT 2003


On Fri, 2003-07-18 at 07:48, Mike C. Fletcher wrote:
> Hi all,
> 
> I'm working on a base meta-type for a plug-in system, and I'd really 
> like to use the same rich-descriptor objects as I've used everywhere 
> else in the system.  Basically these are descriptors that intercept 
> x.name, do various transformations, and then store the values in the 
> instance dictionary.
> 
> Unfortunately:
> 
>  >>> type(t).pluginRole
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "p:\properties\basicproperty\basic.py", line 231, in __get__
>     return self.getDefault( client )
>   File "p:\properties\basicproperty\basic.py", line 256, in getDefault
>     setattr( client, self.name, value )
>   File "p:\properties\basicproperty\basic.py", line 283, in __set__
>     self._setValue( client, value )
>   File "p:\properties\basicproperty\basic.py", line 151, in _setValue
>     client.__dict__[ self.name ] = value
> TypeError: object does not support item assignment
> 
> which would seem to suggest that the only way to use the regular 
> descriptors would be to do the (annoying) '_'+name thing so that there's 
> a proliferation of names in the class (which I *really* don't want).  
> So, does anyone have a pattern which allows setting an attribute on a 
> class which doesn't go through the setattr machinery (i.e. can be used 
> within a descriptor)? 

Maybe you could create just new attribute.  Call it _shadow, perhaps. 
Then the setter does setattr(client._shadow, name, value).  The shadow
could be a plain class like:

class Shadow(object): pass

class Plugin(object):

    def __init__(self):
        self._shadow = Shadow()


May or may not be more elegant, but you can decide for yourself.

  Ian







More information about the Python-list mailing list