reuse validation logic with descriptors

Steven Bethard steven.bethard at gmail.com
Tue Mar 1 13:13:53 EST 2005


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.  
> 
> But I am confused by their behavior on instance of my class. 
> I can only get the approximate behavior by using class variables.
> 
> I am looking for something like:
> 
> class SingleChar(object):
>     def init(self):
>         self._char = None
> 
>     def __set__(self, instance, value):
>         if not len(value) == 1:
>             raise ValueError
>         self._char = value
> 
>     def __get__(self, instance, owner):
>         return self._char
>        
> class Flags(object):
>     def __init__(self):
>         self.a = SingleChar()
>         self.b = SingleChar()
>         
> f = Flags()
> f.a = "a"
> f.b = "bb"
> exceptions.ValueError
> ValueError:
> 
> What I actually get when I try this is f.a and f.b become str instances.
> 
> Meanwhile, I can get this to work, except that a and b are now just class
> attributes.
> 
> class CFlags(object):
>     a = SingleChar()
>     b = SingleChar()
> 
> What is the proper and clean way to accomplish this sort of thing, so that you
> can reuse the logic in for many instance attributes across multiple classes?

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

STeVe



More information about the Python-list mailing list