Created
November 6, 2019 01:28
-
-
Save louisswarren/6c81f6cd495aedfe4be5526a7efd60c8 to your computer and use it in GitHub Desktop.
Decorator for adding obvious assertions to functions
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 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