我正在寻找一种方法来确定是否有一些参数用于解包,我发现了这个:
>>> def func_has_positional_args(func):
std_args = func.func_code.co_argcount
wildcard_args = len(func.func_code.co_varnames) - std_args
if wildcard_args == 2:
return True # yes, has both positional and keyword args
elif wildcard_args == 0:
return False # has neither positional, nor keyword args
else:
raise NotImplementedError('Unable to tell')
>>> func_has_keyword_args = func_has_positional_args
>>> def test1(a, b, *args, **kwargs): pass
>>> func_has_positional_args(test1), func_has_keyword_args(test1)
(True, True)
>>> def test2(a, b): pass
>>> func_has_positional_args(test2), func_has_keyword_args(test2)
(False, False)
>>> def test3(a, b, *args): pass
>>> func_has_positional_args(test3)
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
func_has_positional_args(test3)
File "<pyshell#41>", line 9, in func_has_positional_args
raise NotImplementedError('Unable to tell')
NotImplementedError: Unable to tell
所以我能说出,如果没有位置,也没有关键字参数解包。我也能够判断两者是否存在,但如果只有一个“通配符”,我无法区分实现了哪个“通配符”类型参数。
你能帮我实现以下结果吗?
# Already satisfied with above code:
assert func_has_positional_args(test1) == True
assert func_has_keyword_args(test1) == True
assert func_has_positional_args(test2) == False
assert func_has_keyword_args(test2) == False
# Missing functionality (tests are failing):
assert func_has_positional_args(test3) == True
assert func_has_keyword_args(test3) == False
此外,Python 3是否会针对此功能或其行为进行更改?
答案 0 :(得分:4)
正如mgilson评论的那样,在Python 3.x中使用inspect.getargspec
(更好的是inspect.getfullargspec
)。
import inspect
def func_has_positional_args(func):
spec = inspect.getfullargspec(func)
return bool(spec.varargs) # varargs: name of the * argument or None
def func_has_keyword_args(func):
spec = inspect.getfullargspec(func)
return bool(spec.varkw) # varkw: name of the ** argument or None
示例:
>>> def test1(a, b, *args, **kwargs): pass
...
>>> def test2(a, b): pass
...
>>> def test3(a, b, *args): pass
...
>>> func_has_positional_args(test1)
True
>>> func_has_keyword_args(test1)
True
>>> func_has_positional_args(test2)
False
>>> func_has_keyword_args(test2)
False
>>> func_has_positional_args(test3)
True
>>> func_has_keyword_args(test3)
False