10

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"
Community
  • 1
  • 1
Zango
  • 2,387
  • 3
  • 19
  • 33
  • You can see the source code, can't you? It's obviously 3. What more do you need to know? – S.Lott Oct 12 '10 at 11:18
  • 1
    why don't you try passing `*args` and return `return len(args)` or `return len(filter(None, args))` !!! – shahjapan Oct 12 '10 at 11:36
  • 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" – Zango Oct 12 '10 at 13:22
  • Please **update** your question to include all the background information. – S.Lott Oct 12 '10 at 15:05

3 Answers3

16

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)
RichieHindle
  • 258,929
  • 46
  • 350
  • 392
5

If your method name is sum then sum.func_code.co_argcount will give you number of arguments.

user
  • 5,119
  • 7
  • 45
  • 62
mouad
  • 63,741
  • 17
  • 112
  • 105
  • What downsides are there in using this method? Given the other answers I assume using `inspect` is the preferred way. Why is this? – AnnanFay Sep 16 '16 at 20:42
3
import inspect

print len(inspect.getargspec(sum)[0])
Ned Batchelder
  • 345,440
  • 70
  • 544
  • 649