Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Created November 6, 2019 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louisswarren/6c81f6cd495aedfe4be5526a7efd60c8 to your computer and use it in GitHub Desktop.
Save louisswarren/6c81f6cd495aedfe4be5526a7efd60c8 to your computer and use it in GitHub Desktop.
Decorator for adding obvious assertions to functions
def obviously(v, msg=''):
def outer(f):
def inner(*args, **kwargs):
r = f(*args, **kwargs)
if not v(r):
if msg:
errmsg = f.__name__ + ': ' + msg
else:
errmsg = f.__name__ + ': obviously not true'
raise Exception(errmsg)
return r
return inner
return outer
@obviously(lambda x: 0 <= x <= 1, "Probabilities must be between 0 and 1")
def my_probability_thingy(x):
return x
my_probability_thingy(0)
my_probability_thingy(0.5)
my_probability_thingy(1)
my_probability_thingy(2)
my_probability_thingy(-1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment