Skip to content

Instantly share code, notes, and snippets.

@hunan-rostomyan
Last active September 28, 2020 01:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hunan-rostomyan/18e39ab35d1c147a0d86 to your computer and use it in GitHub Desktop.
Save hunan-rostomyan/18e39ab35d1c147a0d86 to your computer and use it in GitHub Desktop.
Implementing Guards using Decorators in Python
"""
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