views:

538

answers:

2

How can I find the number of arguments of a Python function? I need to know how many normal arguments it has and how many named arguments.

Example:

def someMethod(self, arg1, kwarg1=None):
    pass

This method has 2 arguments and 1 named argument.

+13  A: 
import inspect
inspect.getargspec(someMethod)

see the inspect module

THC4k
+1 -> A handy snippet; thanks very much THC4k :-)
Jon Cage
Generally what you want, but this doesn't work for built-in functions. The only way to know to get this info for builtins is to parse their __doc__ string, which is fugly but doable.
Chris S
+5  A: 

inspect.getargspec()

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.

Changed in version 2.6: Returns a named tuple ArgSpec(args, varargs, keywords, defaults).

See can-you-list-the-keyword-arguments-a-python-function-receives.

gimel