Programmatically determining amount of parameters a function requires - Python [duplicate] Programmatically determining amount of parameters a function requires - Python [duplicate] python python

Programmatically determining amount of parameters a function requires - Python [duplicate]


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.


What you want is in general not possible, because of the use of varargs and kwargs, but inspect.getargspec (Python 2.x) and inspect.getfullargspec (Python 3.x) come close.

  • Python 2.x:

    >>> import inspect>>> def add(a, b=0):...     return a + b...>>> inspect.getargspec(add)(['a', 'b'], None, None, (0,))>>> len(inspect.getargspec(add)[0])2
  • Python 3.x:

    >>> import inspect>>> def add(a, b=0):...     return a + b...>>> inspect.getfullargspec(add)FullArgSpec(args=['a', 'b'], varargs=None, varkw=None, defaults=(0,), kwonlyargs=[], kwonlydefaults=None, annotations={})>>> len(inspect.getfullargspec(add).args)2


In Python 3, use someMethod.__code__.co_argcount

(since someMethod.func_code.co_argcount doesn't work anymore)