Skip to content

Instantly share code, notes, and snippets.

@sgrove
Forked from mikitebeka/gist:337063
Created March 18, 2010 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sgrove/337065 to your computer and use it in GitHub Desktop.
Save sgrove/337065 to your computer and use it in GitHub Desktop.
class Validated:
__fields__ = {} # field -> validator list
def validate(self):
errors = []
for field, validators in self.__fields__.iteritems():
if not hasattr(self, field):
errors.append("field %s missing" % field)
continue
field_errors = []
value = getattr(self, field)
for validator in validators:
try:
validator(value)
except Exception, e:
field_errors.append(str(e))
if field_errors:
errors.append("%s: %s" % (field, ", ".join(field_errors)))
if errors:
assert 0, errors
def is_positive(self, n):
assert (type(n) in (int, long, float)) and (n > 0), "not positive"
class Tunnel(Validated):
__fields__ = {
"status" : [Validated.is_positive]
}
status = 0
host = 0
type = 0
def save(self):
self.validate()
# ...
t = Tunnel()
t.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment