有没有一种方法来调用数错误的参数的Python函数,而不必调用一个TypeError?
-
06-09-2019 - |
题
当你调用一个函数与错误的参数数目,或不在其定义关键字参数,你会得到一个类型错误。我想一段代码采取一个回调和可变参数,基于什么回调支持调用它。这样做的一个方法是,回调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.
有没有这样的事情已经在Python,或者是它的东西,我应该从头开始写?
解决方案
而不是向下挖掘到的细节你自己,你可以检查函数的签名 - 你可能想inspect.getargspec(cb)
究竟要如何使用这些信息,你有指定参数时,为“正常”调用的函数,并不完全清楚给我。假设为了简单,你只关心简单命名指定参数时,你想传递的值是字典d
...
args = inspect.getargspec(cb)[0]
cb( **dict((a,d.get(a)) for a in args) )
也许你想要的东西票友,并能阐述什么?
其他提示
这也许?
def fnVariableArgLength(*args, **kwargs):
"""
- args is a list of non keywords arguments
- kwargs is a dict of keywords arguments (keyword, arg) pairs
"""
print args, kwargs
fnVariableArgLength() # () {}
fnVariableArgLength(1, 2, 3) # (1, 2, 3) {}
fnVariableArgLength(foo='bar') # () {'foo': 'bar'}
fnVariableArgLength(1, 2, 3, foo='bar') # (1, 2, 3) {'foo': 'bar'}
修改您的使用情况
def foo(*args,*kw):
x= kw.get('x',None if len(args) < 1 else args[0])
y= kw.get('y',None if len(args) < 2 else args[1])
z= kw.get('z',None if len(args) < 3 else args[2])
# the rest of foo
foo(1) # should call foo(1, None, None)
foo(y=2) # should call foo(None, 2, None)
foo(1,2,3,4,5) # should call foo(1, 2, 3)
不隶属于 StackOverflow