views:

66

answers:

2

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

def foo(bar, buz):
    pass

magical_way(foo) == ["bar", "buz"]

+6  A: 

Use the inspect method 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.

Alex Martelli
you can also use `return inspect.getargspec(f).args`
gnibbler
@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).
Alex Martelli
Awesome, thanks a lot!
Bemmu
+4  A: 
>>> 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']
gnibbler
Note that `.args` only works in Python 2.6 and up. For older verions you have to use `[0]` instead.
WoLpH
+1 for providing the `magical_way()` function.
Chinmay Kanchi