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
Well we don't actually need inspect here.
>>> 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,)
func.func_code.co_varnames[:func.func_code.co_argcount] since co_varnames is a tuple of all variables present in the function__code__ seems to be backported. func_code also still works.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.
print locals().keys() will return ['arg']. I used print locals.get('arg')"found {thing} in {place}, took {action}, resulting in {result}".format(**locals()) instead of "found {thing} in {place}, took {action}, resulting in {result}".format(thing=thing, place=place, action=action, result=result)locals() returns namespace vars too, eg def func(a,b,c): d=4; print(locals()['d'])f'found {thing} in {place}, took {action}, resulting in {result}'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)]
def foo(first, second, third, *therest):?def decorate(fn): ..., you would simply do fn_params = inspect.signature(fn).parameters in the decorator and use logic to get the argument values in fn's wrapper, def wrapper(*args, **kwargs): ..., which is returned by the decorator.import inspect
def func(a,b,c=5):
pass
>>> inspect.getargspec(func) # inspect.signature(func) in Python 3
(['a', 'b', 'c'], None, None, (5,))
so for getting arguments list alone use:
>>> inspect.getargspec(func)[0]
['a', 'b', 'c']
inspect.getargspec(func) from within func should work just fineinspect.signature