Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of arguments of Python function? [duplicate]

Possible Duplicate:
How to find out the arity of a method in Python

For example I have declared a function:

def sum(a,b,c):
    return a + b + c

I want to get length of arguments of "sum" function.
somethig like this: some_function(sum) to returned 3
How can it be done in Python?

Update:
I asked this question because I want to write a function that accepts another function as a parameter and arguments to pass it.

def funct(anotherFunct, **args): 

and I need to validate:

if(len(args) != anotherFuct.func_code.co_argcount):
    return "error"
like image 433
Zango Avatar asked Oct 12 '10 11:10

Zango


People also ask

How do you count the number of arguments in a function in Python?

We will use the special syntax called *args that is used in the function definition of python. Syntax *args allow us to pass a variable number of arguments to a function. We will use len() function or method in *args in order to count the number of arguments of the function in python.

How many parameters can a Python function have?

In Python 3.7 and newer, there is no limit.

Can a Python function take unlimited number of arguments?

Yes. You can use *args as a non-keyword argument. You will then be able to pass any number of arguments. As you can see, Python will unpack the arguments as a single tuple with all the arguments.

How is variable-length argument passed in Python?

The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.


1 Answers

The inspect module is your friend; specifically inspect.getargspec which gives you information about a function's arguments:

>>> def sum(a,b,c):
...     return a + b + c
...
>>> import inspect
>>> argspec = inspect.getargspec(sum)
>>> print len(argspec.args)
3

argspec also contains details of optional arguments and keyword arguments, which in your case you don't have, but it's worth knowing about:

>>> print argspec
ArgSpec(args=['a', 'b', 'c'], varargs=None, keywords=None, defaults=None)
like image 120
RichieHindle Avatar answered Nov 04 '22 16:11

RichieHindle