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"
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.
In Python 3.7 and newer, there is no limit.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With