Getting list of parameter names inside python function
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: A Thousand Exotic Places Looping v001
--
Chapters
00:00 Getting List Of Parameter Names Inside Python Function
00:24 Answer 1 Score 305
00:42 Answer 2 Score 157
00:57 Answer 3 Score 198
01:15 Accepted Answer Score 494
01:30 Thank you
--
Full question
https://stackoverflow.com/questions/5820...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #parameters
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: A Thousand Exotic Places Looping v001
--
Chapters
00:00 Getting List Of Parameter Names Inside Python Function
00:24 Answer 1 Score 305
00:42 Answer 2 Score 157
00:57 Answer 3 Score 198
01:15 Accepted Answer Score 494
01:30 Thank you
--
Full question
https://stackoverflow.com/questions/5820...
--
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']