Skip to content

Instantly share code, notes, and snippets.

@mittenchops
Last active December 19, 2015 15:28
Show Gist options
  • Save mittenchops/5976127 to your computer and use it in GitHub Desktop.
Save mittenchops/5976127 to your computer and use it in GitHub Desktop.
Python validators. The general form comes exactly from Python in Practice: Create Better Programs Using Concurrency, Libraries, and Patterns Very useful: http://my.safaribooksonline.com/book/programming/python/9780133373271/2dot-structural-design-patterns-in-python/ch02lev1sec4_html
def ensure(name, validate, doc=None):
def decorator(Class):
privateName = "__" + name
def getter(self):
return getattr(self, privateName)
def setter(self, value):
validate(name, value)
setattr(self, privateName, value)
setattr(Class, name, property(getter, setter, doc=doc))
return Class
return decorator
def is_str(name, value):
if not isinstance(value, str):
raise ValueError("{} must be a string".format(name))
def x_is_in_array(vallist):
def x_is_in_array(name,value):
if value not in vallist:
raise ValueError("For field {} : {} is not in {}".format(name,value,vallist))
return x_is_in_array
@ensure('strthing',is_str)
@ensure('arraything',x_is_in_array(ARRAYNAME))
class MEOW(object)
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment