47

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

def foo(bar, buz):
    pass

magical_way(foo) == ["bar", "buz"]
Bemmu
  • 17,849
  • 16
  • 76
  • 93
  • 1
    Duplicate: http://stackoverflow.com/questions/582056/getting-list-of-parameters-inside-python-function, http://stackoverflow.com/questions/218616/getting-method-parameter-names-in-python – Sasha Chedygov Aug 19 '10 at 01:25
  • 3
    Maybe one more is warranted, since I spent a good half an hour trying to Google this without hitting those dupes. – Bemmu Aug 19 '10 at 02: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. – episodeyang Apr 13 '17 at 19:44
  • Btw. I have since learned that it's wrong to say "argument" here, as receiving variables are **parameters**, not arguments. – Bemmu May 31 '19 at 05:47

2 Answers2

75

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.

Nathaniel Jones
  • 939
  • 1
  • 14
  • 25
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
18
>>> 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']
John La Rooy
  • 295,403
  • 53
  • 369
  • 502