【发布时间】:2012-08-08 13:04:31
【问题描述】:
def thefunction(a=1,b=2,c=3):
pass
print allkeywordsof(thefunction) #allkeywordsof doesnt exist
这将给出 [a,b,c]
有allkeywordsof这样的函数吗?
我不能改变里面的任何东西,thefunction
【问题讨论】:
标签: python function introspection
def thefunction(a=1,b=2,c=3):
pass
print allkeywordsof(thefunction) #allkeywordsof doesnt exist
这将给出 [a,b,c]
有allkeywordsof这样的函数吗?
我不能改变里面的任何东西,thefunction
【问题讨论】:
标签: python function introspection
我想你在找inspect.getargspec:
import inspect
def thefunction(a=1,b=2,c=3):
pass
argspec = inspect.getargspec(thefunction)
print(argspec.args)
产量
['a', 'b', 'c']
如果您的函数同时包含位置参数和关键字参数,那么查找关键字参数的名称会稍微复杂一些,但并不难:
def thefunction(pos1, pos2, a=1,b=2,c=3, *args, **kwargs):
pass
argspec = inspect.getargspec(thefunction)
print(argspec)
# ArgSpec(args=['pos1', 'pos2', 'a', 'b', 'c'], varargs='args', keywords='kwargs', defaults=(1, 2, 3))
print(argspec.args)
# ['pos1', 'pos2', 'a', 'b', 'c']
print(argspec.args[-len(argspec.defaults):])
# ['a', 'b', 'c']
【讨论】:
inspect.getargspec(thefunction).args
argspec.args[-len(argspec.defaults):] 这应该被接受,因为它回答了问题。
getargspec 有been deprecated since v3,请改用getfullargspec。
您可以执行以下操作以获得您正在寻找的内容。
>>>
>>> def funct(a=1,b=2,c=3):
... pass
...
>>> import inspect
>>> inspect.getargspec(funct)[0]
['a', 'b', 'c']
>>>
【讨论】:
你想要这样的东西吗:
>>> def func(x,y,z,a=1,b=2,c=3):
pass
>>> func.func_code.co_varnames[-len(func.func_defaults):]
('a', 'b', 'c')
【讨论】:
inspect.getargspec() 也返回非关键字参数。
inspect 并且现在肯定会学习它。 :)
func_code 已重命名为 __code__。