On Fri, Feb 22, 2013 at 10:31 PM, Steven D'Aprano <st...@pearwood.info>wrote:
> 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 > > Thank you for your comments Steven. Yes, I think I should remove property deleter in this case. I would like to use this Person class in another class. For example, if Person class is 'model' in a small MVC-style web application, then where should I place my validation. A view form will be passing parameters to a controller which will create and write Person objects/models. Should the validation be in place at all three levels? I am inclined towards adding integer validation in views, but I am not sure where should I add it in a controller class. Also, it's easy to add integer validation in view form (javascript), but what if I have a more complex format - X509 certificate or some other file-type related validation? Is it OK to validate them only in property setter methods? -- N
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor