views:

2086

answers:

4

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

+13  A: 

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.

unbeknown
+8  A: 
import inspect

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

inspect.getargspec(func)

(['a', 'b', 'c'], None, None, (5,))
Oli
That's not inside the function..
R S
you can do it inside the function too
Oli
+5  A: 

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)]
kmkaplan
A: 

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')
>>> 
simplyharsh