Python list function argument names

Question:

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

def foo(bar, buz):
    pass

magical_way(foo) == ["bar", "buz"]
Asked By: Bemmu

||

Answers:

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.

Answered By: Alex Martelli
>>> 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']
Answered By: John La Rooy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.