Last active
September 28, 2020 01:50
-
-
Save hunan-rostomyan/18e39ab35d1c147a0d86 to your computer and use it in GitHub Desktop.
Implementing Guards using Decorators in Python
This file contains 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
""" | |
Intended to be used as a decorator, UniformGuard | |
ensures that all of the arguments passed to its | |
decorated function `_f` satisfy the guard `g`. | |
""" | |
def UniformGuard(g, e=TypeError): | |
def _g(f): | |
def _f(*args, **kwargs): | |
if not all(map(g, set(args).union(kwargs.values()))): | |
if e: | |
raise e('All arguments must satisfy {}'.format(g)) | |
return None | |
return f(*args, **kwargs) | |
return _f | |
return _g | |
""" | |
Let's use UniformGuard to define a safe division | |
function that doesn't blow up when the denominator | |
is 0. Of course, in actual applications you don't | |
want to silence the guard, so you'll remove `None`. | |
""" | |
def is_nonzero(n): | |
return n < 0 or n > 0 | |
@UniformGuard(is_nonzero, None) | |
def safe_div(a, b): | |
return a / b | |
assert safe_div(4, 2) == 2 | |
assert safe_div(4, 0) == None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment