有没有一种简单的方法可以在Python函数内部获取参数名称列表?
例如:
def func(a,b,c):
print magic_that_does_what_I_want()
>>> func()
['a','b','c']
谢谢
有没有一种简单的方法可以在Python函数内部获取参数名称列表?
例如:
def func(a,b,c):
print magic_that_does_what_I_want()
>>> func()
['a','b','c']
谢谢
实际上在这里我们并不需要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__
。
locals()
返回一个包含本地变量名的字典:
def func(a, b, c):
print(locals().keys())
打印参数列表。如果您使用其他本地变量,这些变量将包含在此列表中。但是您可以在函数开头创建一个副本。
"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 Bronoskylocals()
也会返回命名空间变量,例如 def func(a,b,c): d=4; print(locals()['d'])
。 - Tcllf'在{place}找到了{thing},进行了{action},导致了{result}'
- speedstyle如果你也想要这些值,你可以使用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)]
def foo(first, second, third, *therest):
呢? - MeadowMuffinsimport 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']
func.func_code.co_varnames[:func.func_code.co_argcount]
表示函数中所有变量名的元组,其中包括函数参数的变量名。 - squirrel__code__
似乎被向后移植了。func_code
也仍然可用。 - Def_Os