我如何才能找到一个Python函数的参数的数量?我需要知道它有多少普通参数和多少命名参数。

例子:

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

这个方法有2个参数和1个命名参数。


当前回答

正如其他答案所暗示的那样,只要查询的东西实际上是一个函数,getargespec就能很好地工作。它不适用于内置函数,如open, len等,并会在这些情况下抛出异常:

TypeError: <built-in function open> is not a Python function

下面的函数(受到这个答案的启发)演示了一种变通方法。它返回f期望的参数数:

from inspect import isfunction, getargspec
def num_args(f):
  if isfunction(f):
    return len(getargspec(f).args)
  else:
    spec = f.__doc__.split('\n')[0]
    args = spec[spec.find('(')+1:spec.find(')')]
    return args.count(',')+1 if args else 0

其思想是从__doc__字符串中解析出函数规范。显然,这依赖于所述字符串的格式,因此几乎不是健壮的!

其他回答

import inspect
inspect.getargspec(someMethod)

查看inspect模块

In:

import inspect 

class X:
    def xyz(self, a, b, c): 
        return 

print(len(inspect.getfullargspec(X.xyz).args))

Out:

4


注意:如果xyz不在类X中,并且没有“self”,只有“a, b, c”,那么它将打印3。

对于3.5以下的python,您可能需要替换inspect。通过检查获得全部规格。在上面的代码中获取目标规格。

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. Changed in version 2.6: Returns a named tuple ArgSpec(args, varargs, keywords, defaults).

看到can-you-list-the-keyword-arguments-a-python-function-receives。

对于那些想要在Python 2和Python 3.6+之间以可移植的方式做到这一点的人来说,有一个好消息:使用inspect.getfullargspec()方法。它在Python 2中都可以工作。X和3.6+

正如吉姆·法萨拉基斯·希利亚德(Jim Fasarakis Hilliard)等人指出的,过去是这样的: 1. 在Python 2中。X:使用inspect.getargspec() 2. 在Python 3中。X:使用签名,因为getargespec()和getfulllargspec()已弃用。

然而,从Python 3.6开始(根据流行需求?),事情已经朝着更好的方向变化:

从Python 3文档页:

inspect.getfullargspec(函数) 在3.6版更改:此方法以前在Python 3.5中被记录为不赞成signature(),但为了恢复从遗留的getargspec() API迁移的单源Python 2/3代码明确支持的标准接口,该决定已被撤销。

someMethod.func_code.co_argcount

或者,如果当前函数名未确定:

import sys

sys._getframe().func_code.co_argcount