Here’s a nifty introspection feature that I didn’t know about. Python has a really nice inspect module that lets you peek at all kinds of things.

Today’s question: How do I get a list of the arguments for a function?

Answer: inspect.getargspec(func). From the documentation:

Get the names and default values of a function’s arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). args is a list of the argument names (it may contain nested lists). varargs and varkw are the names of the * and ** arguments or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.

And here’s what it looks like in action:

Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> def foo(a, b):
...   pass
>>> def bar(c=None, d=5):
...   pass
>>> def baz(*args, **kwargs):
...   pass
>>> inspect.getargspec(foo)
(['a', 'b'], None, None, None)
>>> inspect.getargspec(bar)
(['c', 'd'], None, None, (None, 5))
>>> inspect.getargspec(baz)
([], 'args', 'kwargs', None)

Thanks go to Jason Collins for kicking off this search for new knowledge :)