[英]Passing unknown args and kwargs to function in python
I have an object that takes in a function name func, args, and kwargs, and at some point runs 我有一个对象,它接受一个函数名func,args和kwargs,并在某些时候运行
func(*args, **kwargs)
The issue is, if func requires no args/kwargs, args/kwargs default to None, which leads to a TypeError. 问题是,如果func不需要args / kwargs,则args / kwargs默认为None,这会导致TypeError。 For example, if the function required no parameters, args, kwargs default to None:
例如,如果函数不需要参数,则args,kwargs默认为None:
def test():
pass
args = None
kwargs = None
test(*args, **kwargs)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-b9618694fbf2> in <module>()
----> 1 test(*args, **kwargs)
TypeError: test() argument after ** must be a mapping, not NoneType
I'm sure there's a good way to solve this without cascading if statements checking if args/kwargs exist, each with its own function call, but I'm not sure how. 我确定有一个很好的方法来解决这个问题,如果没有级联if语句检查是否存在args / kwargs,每个都有自己的函数调用,但我不知道如何。 The main goal is to pass a function, and its unknown parameters to an object, which will then use them in a method later.
主要目标是将一个函数及其未知参数传递给一个对象,然后在一个方法中使用它们。
Edited: added an example for clarity 编辑:为了清晰起见添加了一个例子
The issue is, if func requires no args/kwargs, args/kwargs default to None, which leads to a TypeError.
问题是,如果func不需要args / kwargs,则args / kwargs默认为None,这会导致TypeError。
This is not true: 这不是真的:
def func1(*args, **kwargs)
print args, kwargs
will print 将打印
() {}
In reverse, 相反,
def func2(): pass
can be perfectly called with 可以完美地称之为
func2(*(), **{})
So just change your args
and kwargs
variables and you're fine. 所以只需更改你的
args
和kwargs
变量就可以了。
Avoid to default your args
and kwargs
to None
. 避免将你的
args
和kwargs
默认为None
。
args
should be a tuple : args = ()
args
应该是一个元组: args = ()
kwargs
should be a dictionnary : kwargs = {}
kwargs
应该是一个词典: kwargs = {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.