reuse validation logic with descriptors

Steve Holden steve at holdenweb.com
Tue Mar 1 17:08:12 EST 2005


David S. wrote:
> Steven Bethard <steven.bethard <at> gmail.com> writes:
> 
> 
>>David S. wrote:
>>
>>>I am looking for a way to implement the same simple validation on many 
>>>instance attributes and I thought descriptors
>>>(http://users.rcn.com/python/download/Descriptor.htm) looked like the 
>>>right tool.  
>>>
>>
>>Looks like you're trying to reinvent the property descriptor.  Try using 
>>the builtin property instead:
>>
>>py> def getchar(self):
>>...     if not hasattr(self, '_char'):
>>...         self._char = None
>>...     return self._char
>>...
>>py> def setchar(self, value):
>>...     if not len(value) == 1:
>>...         raise ValueError
>>...     self._char = value
>>...
>>py> singlechar = property(getchar, setchar)
>>py> class Flags(object):
>>...     a = singlechar
>>...     b = singlechar
>>...
>>py> f = Flags()
>>py> f.a = "a"
>>py> f.b = "bb"
>>Traceback (most recent call last):
>>   File "<interactive input>", line 1, in ?
>>   File "<interactive input>", line 3, in setchar
>>ValueError
>>
> 
> 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
> ...
> py> f = Flags()
> py> f.a = "a"
> 
> Now f.a.__class__.__name__ returns 'str'.  So the property was not 
> used at all.
> 
You want assignment to a method-local variable to turn an attribute into 
a property? That's programming with a magic wand ...

> 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__.  
> 
That will depend on the value returned by property access, surely?

I suspect you are a little confused about properties and descriptors.

regards
  Steve
-- 
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005                      http://www.pycon.org/
Steve Holden                           http://www.holdenweb.com/



More information about the Python-list mailing list