On 23/02/13 10:50, neubyr wrote:
I would like to validate data attributes before the object is instantiated
or any changes thereafter. For example, following is a simple Person class
with name and age attributes. I would like to validate whether age is an
integer before it is added/changed in the object's dictionary. I have taken
a simple integer validation example, but it could be something like
DateField validation or X509 certificate validation as well. Following is
my example code:


class Person(object):
   def __init__(self,name,age):
     self.name = name
     self.age = age

   def get_age(self):
     return self._age

   def set_age(self,val):
     try:
       int(val)
       self._age = val
     except ValueError:
         raise Exception('Invalid value for age')

The setter is unnecessarily complicated. Just let the ValueError, or TypeError, 
or any other error, propagate:

    def set_age(self,val):
        self._age = int(val)


This will allow the user to pass ages as strings, which I assume you want because that's 
what your code above does. instance.age = "6" will set the age to the int 6. If 
all you want to accept are ints, and nothing else:


    def set_age(self,val):
        if isinstance(val, int):
            self._age = val
        else:
            raise TypeError('expected an int, but got %r' % val)



   def del_age(self):
     del self._age

   age = property(get_age,set_age,del_age)


In general, you would leave out the property deleter. I find that in general if 
you're validating attributes, you want them to be present and valid, so 
deleting should be an error.


--
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to