Is there an easy way to be inside a python function and get a list of the parameter names?
For example:
def func(a,b,c):
print magic_that_does_what_I_want()
>>> func()
['a','b','c']
Thanks
Is there an easy way to be inside a python function and get a list of the parameter names?
For example:
def func(a,b,c):
print magic_that_does_what_I_want()
>>> func()
['a','b','c']
Thanks
locals() returns a dictionary with local names:
def func(a,b,c):
print locals().keys()
prints the list of parameters. If you use other local variables those will be included in this list. But you could make a copy at the beginning of your function.
import inspect
def func(a,b,c=5):
pass
inspect.getargspec(func)
(['a', 'b', 'c'], None, None, (5,))
If you also want the values you can use the inspect
module
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)]
Well we don't actually need inspect
here.
>>> func = lambda x, y: (x, y)
>>>
>>> func.func_code.co_argcount
2
>>> func.func_code.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
... print func2.func_code.co_varnames
... pass # Other things
...
>>> func2(3,3)
('x', 'y')
>>>