Getting list of parameter names inside python function
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2
--
Chapters
00:00 Question
00:35 Accepted answer (Score 471)
01:13 Answer 2 (Score 283)
01:38 Answer 3 (Score 188)
02:04 Answer 4 (Score 145)
02:16 Thank you
--
Full question
https://stackoverflow.com/questions/5820...
Question links:
[Getting method parameter names in python]: https://stackoverflow.com/questions/2186...
Answer 1 links:
[locals()]: https://docs.python.org/library/function...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #parameters
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2
--
Chapters
00:00 Question
00:35 Accepted answer (Score 471)
01:13 Answer 2 (Score 283)
01:38 Answer 3 (Score 188)
02:04 Answer 4 (Score 145)
02:16 Thank you
--
Full question
https://stackoverflow.com/questions/5820...
Question links:
[Getting method parameter names in python]: https://stackoverflow.com/questions/2186...
Answer 1 links:
[locals()]: https://docs.python.org/library/function...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #parameters
#avk47
ACCEPTED ANSWER
Score 494
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,)
ANSWER 2
Score 305
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.
ANSWER 3
Score 198
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)]
ANSWER 4
Score 157
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']