Created
February 22, 2021 00:20
-
-
Save leveled/daf54ad044285c6efbbf2681159619ae to your computer and use it in GitHub Desktop.
Validate function annotations in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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