Skip to content

Instantly share code, notes, and snippets.

@leveled
Created February 22, 2021 00:20
Show Gist options
  • Save leveled/daf54ad044285c6efbbf2681159619ae to your computer and use it in GitHub Desktop.
Save leveled/daf54ad044285c6efbbf2681159619ae to your computer and use it in GitHub Desktop.
Validate function annotations in Python
def validate(func, locals):
for var, test in func.__annotations__.items():
value = locals[var]
try:
pr=test.__name__+': '+test.__docstring__
except AttributeError:
pr=test.__name__
msg = '{}=={}; Test: {}'.format(var, value, pr)
assert test(value), msg
def between(lo, hi):
def _between(x):
return lo <= x <= hi
_between.__docstring__='must be between {} and {}'.format(lo,hi)
return _between
def f(x: between(3,10), y:lambda _y: isinstance(_y,int)):
validate(f, locals())
print(x,y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment