reuse validation logic with descriptors

David S. davidschein at alumni.tufts.edu
Tue Mar 1 12:33:51 EST 2005


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?

Thanks, David S.




More information about the Python-list mailing list