I'd like advice/opinions on when it is appropriate to do attribute/property validation in python. I'm coming from a C#/Java background, where of course tons of "wasted" code is devoted to property validation. Here is a toy example illustrating my question:
# Example: mixing instance attributes with properties. Is it pythonic to # validate property data in setters? Since tens and ones are never # validated, the class can be "broken" by setting these directly class SillyDecimal(object): """A silly class to represent an integer from 0 - 99.""" def __init__(self, arg=17): if isinstance(arg, tuple): self.tens = arg[0] self.ones = arg[1] else: self.number = arg def getNumber(self): return self.tens*10 + self.ones def setNumber(self, value): if value < 0 or value > 99: raise ArgumentException("Must in [0, 99]") self.tens = value // 10 self.ones = value % 10 number = property(getNumber, setNumber, None, "Complete number, [0-99]") x = SillyDecimal() x.number, x.tens, x.ones # returns (17, 7, 1) Even though "tens", "ones" and "number" all appear as attributes, only "number" has its input validated. Since the class is designed to only hold numbers 0 - 99, one can 'break' it by setting self.tens=11, for example. Should tens and ones be made into full-fledged properties and validated? Should number have no validation? Is it more pythonic to encapsulate tightly, or rely on "responsible use." Marcus -- http://mail.python.org/mailman/listinfo/python-list