How to Find the Number of Arguments of a Python Function

How can I find the number of arguments of a Python function?

The previously accepted answer has been deprecated as of Python 3.0. Instead of using inspect.getargspec you should now opt for the Signature class which superseded it.

Creating a Signature for the function is easy via the signature function:

from inspect import signature

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

sig = signature(someMethod)

Now, you can either view its parameters quickly by string it:

str(sig)  # returns: '(self, arg1, kwarg1=None)'

or you can also get a mapping of attribute names to parameter objects via sig.parameters.

params = sig.parameters 
print(params['kwarg1']) # prints: kwarg1=20

Additionally, you can call len on sig.parameters to also see the number of arguments this function requires:

print(len(params))  # 3

Each entry in the params mapping is actually a Parameter object that has further attributes making your life easier. For example, grabbing a parameter and viewing its default value is now easily performed with:

kwarg1 = params['kwarg1']
kwarg1.default # returns: None

similarly for the rest of the objects contained in parameters.


As for Python 2.x users, while inspect.getargspec isn't deprecated, the language will soon be :-). The Signature class isn't available in the 2.x series and won't be. So you still need to work with inspect.getargspec.

As for transitioning between Python 2 and 3, if you have code that relies on the interface of getargspec in Python 2 and switching to signature in 3 is too difficult, you do have the valuable option of using inspect.getfullargspec. It offers a similar interface to getargspec (a single callable argument) in order to grab the arguments of a function while also handling some additional cases that getargspec doesn't:

from inspect import getfullargspec

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

args = getfullargspec(someMethod)

As with getargspec, getfullargspec returns a NamedTuple which contains the arguments.

print(args)
FullArgSpec(args=['self', 'arg1', 'kwarg1'], varargs=None, varkw=None, defaults=(None,), kwonlyargs=[], kwonlydefaults=None, annotations={})

How to determine the number of arguments passed to function?

You can define the function as follows to get the values of the arguments:

def function(*args):
for i in range(len(args)):
print(args[i])

function(3, 5, 8)

Here is the result:

3
5
8

That is, args[i] receives the value of the i-th parameter passed to function.

Check the number of parameters passed in Python function

You can do this by using locals()

It is important to note, that this should be done as ultimately, your first step in your method. If you introduce a new variable in your method, you will change your results. So make sure you follow it this way:

def a(a, b, c):
# make this your first statement
print(len(locals()))

If you did this:

def a(a, b, c):
z = 5
print(len(locals()))

You would end up getting 4, which would not be right for your expected results.

Documentation on locals()

Programmatically determining amount of parameters a function requires - Python

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.

Getting list of parameter names inside python function

Well we don't actually need inspect here.

>>> func = lambda x, y: (x, y)
>>>
>>> func.__code__.co_argcount
2
>>> func.__code__.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
... print(func2.__code__.co_varnames)
... pass # Other things
...
>>> func2(3,3)
('x', 'y')
>>>
>>> func2.__defaults__
(3,)

For Python 2.5 and older, use func_code instead of __code__, and func_defaults instead of __defaults__.

How to get the number of args of a built-in function in Python?

Take a look at the function below copied from here. This may be the best you can do. Note the comments about inspect.getargspec.

def describe_builtin(obj):
""" Describe a builtin function """

wi('+Built-in Function: %s' % obj.__name__)
# Built-in functions cannot be inspected by
# inspect.getargspec. We have to try and parse
# the __doc__ attribute of the function.
docstr = obj.__doc__
args = ''

if docstr:
items = docstr.split('\n')
if items:
func_descr = items[0]
s = func_descr.replace(obj.__name__,'')
idx1 = s.find('(')
idx2 = s.find(')',idx1)
if idx1 != -1 and idx2 != -1 and (idx2>idx1+1):
args = s[idx1+1:idx2]
wi('\t-Method Arguments:', args)

if args=='':
wi('\t-Method Arguments: None')

print

Can a variable number of arguments be passed to a function?

Yes. You can use *args as a non-keyword argument. You will then be able to pass any number of arguments.

def manyArgs(*arg):
print "I was called with", len(arg), "arguments:", arg

>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2, 3)
I was called with 3 arguments: (1, 2, 3)

As you can see, Python will unpack the arguments as a single tuple with all the arguments.

For keyword arguments you need to accept those as a separate actual argument, as shown in Skurmedel's answer.

Is it possible to get how many positional arguments does a function need in Python 3?

You can use the inspect module for this:

import inspect

def count_positional_args_required(func):
signature = inspect.signature(func)
empty = inspect.Parameter.empty
total = 0
for param in signature.parameters.values():
if param.default is empty:
total += 1
return total

def a():pass # 0 positional arguments
def b(x):pass # 1 positional argument
def c(x=0):pass # 0 positional arguments
def d(x,y=0):pass # 1 positional argument
def e(x,y):pass # 2 positional arguments
def f(x=0,y=0):pass # 0 positional arguments

for func in [a,b,c,d,e,f]:
print(count_positional_args_required(func))

EDIT:
The above only works for non-built-in functions.



Related Topics



Leave a reply



Submit