获取Python函数内参数名称列表

388

有没有一种简单的方法可以在Python函数内部获取参数名称列表?

例如:

def func(a,b,c):
    print magic_that_does_what_I_want()

>>> func()
['a','b','c']

谢谢

4个回答

480

实际上在这里我们并不需要inspect

>>> func = lambda x, y: (x, y)
>>> 
>>> func.__code__.co_argcount
2
>>> func.__code__.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
...  print(func2.__code__.co_varnames)
...  pass # Other things
... 
>>> func2(3,3)
('x', 'y')
>>> 
>>> func2.__defaults__
(3,)

对于Python 2.5及更早版本,请使用func_code代替__code__,以及func_defaults代替__defaults__


47
这段话的意思是:func.func_code.co_varnames[:func.func_code.co_argcount] 表示函数中所有变量名的元组,其中包括函数参数的变量名。 - squirrel
32
在Python3中,这将是func.code.co_varnames。 - michaelJohn
2
这仅适用于非“内置函数或方法”。 - MagSec
3
我使用Python 2.7.8版本,而且__code__似乎被向后移植了。func_code也仍然可用。 - Def_Os
7
请使用inspect模块,否则你的代码在3.4及以上版本中无法与functools.wraps正常工作。请参考https://dev59.com/lnVC5IYBdhLWcg3w51ry。 - Brian McCutchon
显示剩余6条评论

296

locals() 返回一个包含本地变量名的字典:

def func(a, b, c):
    print(locals().keys())

打印参数列表。如果您使用其他本地变量,这些变量将包含在此列表中。但是您可以在函数开头创建一个副本。


3
“print locals().keys()”将返回“['arg']”。我使用了“print locals.get('arg')”。 - yurisich
13
谢谢!我对"found {thing} in {place}, took {action}, resulting in {result}".format(**locals())这种写法产生了新的喜爱,因为它比起"found {thing} in {place}, took {action}, resulting in {result}".format(thing=thing, place=place, action=action, result=result)更加简洁。 - Bruno Bronosky
7
注意,locals() 也会返回命名空间变量,例如 def func(a,b,c): d=4; print(locals()['d']) - Tcll
5
为什么不直接使用f-string?f'在{place}找到了{thing},进行了{action},导致了{result}' - speedstyle
2
@speedstyle f-strings是在Python 3.6中引入的。该评论来自3.5版本。(是的,f-strings要好得多:D) - GeeTransit
显示剩余3条评论

193

如果你也想要这些值,你可以使用inspect模块。

import inspect

def func(a, b, c):
    frame = inspect.currentframe()
    args, _, _, values = inspect.getargvalues(frame)
    print 'function name "%s"' % inspect.getframeinfo(frame)[2]
    for i in args:
        print "    %s = %s" % (i, values[i])
    return [(i, values[i]) for i in args]

>>> func(1, 2, 3)
function name "func"
    a = 1
    b = 2
    c = 3
[('a', 1), ('b', 2), ('c', 3)]

14
Kelly Yancey的博客(http://kbyanc.blogspot.com/2007/07/python-aggregating-function-arguments.html)有一篇很棒的文章详细解释了这个问题,并给出了一个稍微精细一些的版本,还提供了与其他解决方法(如unbeknown的解决方案)的比较。建议阅读。 - dan mackinlay
那么 def foo(first, second, third, *therest): 呢? - MeadowMuffins
2
如何在装饰器中使用此功能? - JDOaktown

152
import inspect

def func(a,b,c=5):
    pass

>>> inspect.getargspec(func)  # inspect.signature(func) in Python 3
(['a', 'b', 'c'], None, None, (5,))

只需使用以下方法获取参数列表:

>>> inspect.getargspec(func)[0]
['a', 'b', 'c']

1
那不在函数内部。 - R S
15
你也可以在函数内部完成它。 - Oli
12
这实际上更好,因为它展示了如何获取你自己没有编写的方法的参数。 - Dannid
1
但是如何在函数内部完成这个操作呢? - Unverified Contact
6
@DavidC 更新的链接 inspect.signature。 意思是提供了更新后的 inspect.signature 链接,可以在这个链接中找到相关信息。 - A T
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接