And*_*rov 1 python invocation apply
当您调用具有错误数量的参数的函数或使用不在其定义中的关键字参数时,您将获得TypeError.我想要一段代码来进行回调,并根据回调支持的内容,使用变量参数调用它.一种方法是,对于回调cb,使用cb.__code__.cb_argcount和cb.__code__.co_varnames,但我宁愿将其抽象为类似的东西apply,但只应用"适合"的参数.
例如:
def foo(x,y,z):
pass
cleanvoke(foo, 1) # should call foo(1, None, None)
cleanvoke(foo, y=2) # should call foo(None, 2, None)
cleanvoke(foo, 1,2,3,4,5) # should call foo(1, 2, 3)
# etc.
Run Code Online (Sandbox Code Playgroud)
在Python中是否有这样的东西,或者我应该从头开始编写什么?
您可以检查函数的签名 - 而不是自己深入研究细节inspect.getargspec(cb).
确切地说,如何使用该信息以及您拥有的args来"正确"调用该函数,对我来说并不完全清楚.假设为了简单起见,你只关心简单的命名args,你想传递的值是dict d...
args = inspect.getargspec(cb)[0]
cb( **dict((a,d.get(a)) for a in args) )
Run Code Online (Sandbox Code Playgroud)
也许你想要更高级的东西,并且可以详细说明究竟是什么?