Skip to content

Instantly share code, notes, and snippets.

@anfedorov
Created April 10, 2009 16:04
Show Gist options
  • Save anfedorov/93137 to your computer and use it in GitHub Desktop.
Save anfedorov/93137 to your computer and use it in GitHub Desktop.
def validate(schema):
def validator(validatee):
for x in schema:
isValid = schema[x]
if type(validatee[x]) == isValid: continue
elif type(isValid) != type and hasattr(isValid, '__call__'):
if isValid(validatee[x]): continue
return False
return True
return validator
# Example:
>>> isValid = validate({ 'foo': str, 'bar': int})
>>> isValid({ 'foo': '', 'bar': 3})
True
>>> isValid({ 'foo': '', 'bar': '3'})
False
>>> isAlsoValid = validate({ 'a': isValid, 'b': str })
>>> isAlsoValid({ 'a': { 'foo': 'a string', 'bar': '3'}, 'b': 'another string' })
False
>>> isAlsoValid({ 'a': { 'foo': 'a string', 'bar': 3}, 'b': 'another string' })
True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment