reuse validation logic with descriptors

David S. davidschein at alumni.tufts.edu
Tue Mar 1 20:35:38 CET 2005


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.

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__.  

Again, thanks,
David S.





More information about the Python-list mailing list