Python list function argument names
58,761
Solution 1
Use the inspect module from Python's standard library (the cleanest, most solid way to perform introspection).
Specifically, inspect.getargspec(f)
returns the names and default values of f
's arguments -- if you only want the names and don't care about special forms *a
, **k
,
import inspect
def magical_way(f):
return inspect.getargspec(f)[0]
completely meets your expressed requirements.
Solution 2
>>> import inspect
>>> def foo(bar, buz):
... pass
...
>>> inspect.getargspec(foo)
ArgSpec(args=['bar', 'buz'], varargs=None, keywords=None, defaults=None)
>>> def magical_way(func):
... return inspect.getargspec(func).args
...
>>> magical_way(foo)
['bar', 'buz']
Author by
Bemmu
Updated on July 09, 2022Comments
-
Bemmu almost 2 years
Is there a way to get the parameter names a function takes?
def foo(bar, buz): pass magical_way(foo) == ["bar", "buz"]
-
Sasha Chedygov almost 14 years
-
Bemmu almost 14 yearsMaybe one more is warranted, since I spent a good half an hour trying to Google this without hitting those dupes.
-
episodeyang about 7 yearsThis is the first hit on Google now, thanks to the way OP asked the question. Making answers easier to find by framing the question better is definitely relevant to UX of those looking for answers.
-
Bemmu about 5 yearsBtw. I have since learned that it's wrong to say "argument" here, as receiving variables are parameters, not arguments.
-
-
John La Rooy almost 14 yearsyou can also use
return inspect.getargspec(f).args
-
Wolph almost 14 yearsNote that
.args
only works in Python 2.6 and up. For older verions you have to use[0]
instead. -
Alex Martelli almost 14 years@gnibbler, true, in Python 2.6 or better only (so not if you're using Python with App Engine (or apps embedding Python 2.5 or earlier); I gave the approach that works in any Python (since 2.1 when
inspect
was added to the standard library). -
Chinmay Kanchi almost 14 years+1 for providing the
magical_way()
function. -
Luke Murray over 7 yearsmaybe you can edit this since getargspec is now deprecated and inspect.signature() is favored instead
-
juan Isaza about 7 yearsinspect.getargspec is deprecated as of Python 3.6. Instead one should use inspect.signature. Any one knows how to use it?, thanks
-
lovesh about 7 years@juanIsaza
inspect.signature(f).parameters
-
Dasmowenator over 6 yearsYou can also inspect a constructor's arguments using "inspect.getargspec(MyClass.__init__)[0]" as mentioned here: stackoverflow.com/a/36849919/367544
-
TheGrimmScientist almost 5 yearsthat function name tho
-
Mauricio Arboleda over 3 years@juanIsaza alternative you can use inspect.getfullargspec(f).args or inspect.getfullargspec(f)[0] (python 3.7)