【发布时间】:2014-01-29 00:38:28
【问题描述】:
我正在寻找一种方法来确定某些参数是否用于解包,我发现了这个:
>>> 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 对此功能或其行为有什么改变吗?
【问题讨论】:
-
...我不确定我是否真的密切关注这个,但你不是在寻找
inspect.getargspec吗?你所做的有什么不同? -
@mgilson:是的,靶心;)似乎我太专注于查找函数属性而不是查看
inspect模块...您愿意将其发布为答案吗?
标签: python python-3.x introspection argument-passing keyword-argument