Last active
August 29, 2015 14:25
-
-
Save edouardp/b06908ffe875efb55017 to your computer and use it in GitHub Desktop.
Python decorator to raise a RuntimeError if any of the arguments are None when called
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
import inspect | |
def raise_on_none(f): | |
arg_spec = inspect.getargspec(f) | |
def new_f(*args, **kwargs): | |
bound_args = inspect.getcallargs(f, *args, **kwargs) | |
if(any([bound_args[a]==None for a in arg_spec.args])): | |
raise RuntimeError('Named arg is None') | |
if(arg_spec.keywords != None): | |
if(any([a==None for a in bound_args[arg_spec.keywords].values()])): | |
raise RuntimeError('Keyword arg is None') | |
if(arg_spec.varargs != None): | |
if(any([a==None for a in bound_args[arg_spec.varargs]])): | |
raise RuntimeError('Var arg is None') | |
return f(*args, **kwargs) | |
new_f.spec = arg_spec | |
return new_f | |
# Example | |
@raise_on_none | |
def fn_x(a,b,c,d=None,e=None): | |
print a,b,c,d,e | |
fn_x(1,2,3,4) | |
# -> RuntimeError: Named arg is None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment