mar*_*ius 5 python inspect keyword-argument
当忘记将某些参数传递给函数时,Python给出了唯一有用的消息"myfunction()接受X参数(给定Y)".有没有办法弄清楚缺少的参数的名称,并告诉用户?就像是:
try:
#begin blackbox
def f(x,y):
return x*y
f(x=1)
#end blackbox
except Exception as e:
#figure out the missing keyword argument is called "y" and tell the user so
Run Code Online (Sandbox Code Playgroud)
假设开始blackbox和end blackbox之间的代码对于异常处理程序是未知的.
编辑:正如我在下面指出的那样,Python 3已经内置了这个功能.让我扩展一下这个问题,是否有一种(可能是丑陋和hacky)方法在Python 2.x中执行此操作?
except TypeError as e:
import inspect
got_args = int(re.search("\d+.*(\d+)",str(e)).groups()[0])
print "missing args:",inspect.getargspec(f).args[got_args:]
Run Code Online (Sandbox Code Playgroud)
更好的方法是装饰器
def arg_decorator(fn):
def func(*args,**kwargs):
try:
return fn(*args,**kwargs)
except TypeError:
arg_spec = inspect.getargspec(fn)
missing_named = [a for a in arg_spec.args if a not in kwargs]
if arg_spec.defaults:
missing_args = missing_named[len(args): -len(arg_spec.defaults) ]
else:
missing_args = missing_named[len(args):]
print "Missing:",missing_args
return func
@arg_decorator
def fn1(x,y,z):
pass
def fn2(x,y):
pass
arged_fn2 = arg_decorator(fn2)
fn1(5,y=2)
arged_fn2(x=1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1162 次 |
| 最近记录: |