reuse validation logic with descriptors

Michael Spencer mahs at telcopartners.com
Tue Mar 1 15:29:58 EST 2005


David S. wrote:

> 
> This still fails to work for instances variables of the class.  That is 
> if I use your property in the following:
> py> ...class Flags(object):
> ...        def __init__(self): 
> ...             a = singlechar
> ...

you should write that as:
class Flags(object):
     a = singlechar
     def __init__(self):
         a = "a"


> py> f = Flags()
> py> f.a = "a"
> 
> Now f.a.__class__.__name__ returns 'str'.  So the property was not 
> used at all.
> 
> Also, it seems that using a property, I can not do the other useful 
> things I can do with a proper class, like provide an __init__, __str__, 
> or __repr__.  
>
If you want "other useful things" then you can write a custom descriptor, like:

from weakref import WeakKeyDictionary

class SingleChar(object):
     def __init__(self):
         """raises ValueError if attribute is set to something
         other than a single char"""
         self.objdict = WeakKeyDictionary()
     def __get__(self, obj, cls):
         if isinstance(obj, cls):
             try:
                 return self.objdict[obj]
             except KeyError:
                 raise AttributeError, "property not set"
         else:
             return self
     def __set__(self, obj, value):
         if isinstance(value, str) and len(value) == 1:
             self.objdict[obj] = value
         else:
             raise ValueError, value

class Flags(object):
     a = SingleChar()
     b = SingleChar()


See also: http://groups-beta.google.com/group/comp.lang.python/msg/30c61a30a90133d2

for another example of this approach

Michael
> Again, thanks,
> David S.
> 
> 




More information about the Python-list mailing list