开发者

Length of arguments of Python function? [duplicate]

This question already has answers here: 开发者_StackOverflow社区 Closed 12 years ago.

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"


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 your method name is sum then sum.func_code.co_argcount will give you number of arguments.


import inspect

print len(inspect.getargspec(sum)[0])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜