48

Is there a way to get the parameter names a function takes?

def foo(bar, buz):
    pass

magical_way(foo) == ["bar", "buz"]
4
  • 1
    Duplicate: stackoverflow.com/questions/582056/…, stackoverflow.com/questions/218616/… Commented Aug 19, 2010 at 1:25
  • 3
    Maybe one more is warranted, since I spent a good half an hour trying to Google this without hitting those dupes. Commented Aug 19, 2010 at 2:03
  • 3
    This 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. Commented Apr 13, 2017 at 19:44
  • Btw. I have since learned that it's wrong to say "argument" here, as receiving variables are parameters, not arguments. Commented May 31, 2019 at 5:47

2 Answers 2

76

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.

Sign up to request clarification or add additional context in comments.

8 Comments

you can also use return inspect.getargspec(f).args
maybe you can edit this since getargspec is now deprecated and inspect.signature() is favored instead
inspect.getargspec is deprecated as of Python 3.6. Instead one should use inspect.signature. Any one knows how to use it?, thanks
@juanIsaza inspect.signature(f).parameters
@juanIsaza alternative you can use inspect.getfullargspec(f).args or inspect.getfullargspec(f)[0] (python 3.7)
|
20
>>> 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']

2 Comments

Note that .args only works in Python 2.6 and up. For older verions you have to use [0] instead.
+1 for providing the magical_way() function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.