如何找到Python函数的参数数量?

问题:如何找到Python函数的参数数量?

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

例:

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

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

How can I find the number of arguments of a Python function? I need to know how many normal arguments it has and how many named arguments.

Example:

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

This method has 2 arguments and 1 named argument.


回答 0

于接受的答案已于弃用Python 3.0inspect.getargspec现在,您应该选择Signature取代它的类,而不是使用它。

创建功能的签名是通过简单的signature功能

from inspect import signature

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

sig = signature(someMethod)

现在,您可以通过以下方式快速查看其参数str

str(sig)  # returns: '(self, arg1, kwarg1=None)'

或者您也可以通过来获取属性名称到参数对象的映射sig.parameters

params = sig.parameters 
print(params['kwarg1']) # prints: kwarg1=20

此外,你可以叫lensig.parameters也看到的参数此功能,需要数量:

print(len(params))  # 3

params映射中的每个条目实际上都是一个具有更多属性的Parameter对象,使您的生活更加轻松。例如,现在可以轻松地执行以下操作来获取参数并查看其默认值:

kwarg1 = params['kwarg1']
kwarg1.default # returns: None

包含在中的其余对象也类似parameters


对于Python 2.x用户,虽然inspect.getargspec 不建议弃用,但该语言很快就会成为:-)。该Signature类在该2.x系列中不可用,也不会提供。因此,您仍然需要使用inspect.getargspec

至于Python 2和3之间的转换,如果你有一些代码依赖的接口getargspec在Python 2切换到signature3是太难了,你必须将有价值的选择使用inspect.getfullargspec。它提供了与getargspec(单个可调用参数)相似的接口,以获取函数的参数,同时还处理某些其他情况,这些getargspec情况不是:

from inspect import getfullargspec

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

args = getfullargspec(someMethod)

与一样getargspecgetfullargspec返回NamedTuple包含参数的。

print(args)
FullArgSpec(args=['self', 'arg1', 'kwarg1'], varargs=None, varkw=None, defaults=(None,), kwonlyargs=[], kwonlydefaults=None, annotations={})

The previously accepted answer has been deprecated as of Python 3.0. Instead of using inspect.getargspec you should now opt for the Signature class which superseded it.

Creating a Signature for the function is easy via the signature function:

from inspect import signature

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

sig = signature(someMethod)

Now, you can either view its parameters quickly by string it:

str(sig)  # returns: '(self, arg1, kwarg1=None)'

or you can also get a mapping of attribute names to parameter objects via sig.parameters.

params = sig.parameters 
print(params['kwarg1']) # prints: kwarg1=20

Additionally, you can call len on sig.parameters to also see the number of arguments this function requires:

print(len(params))  # 3

Each entry in the params mapping is actually a Parameter object that has further attributes making your life easier. For example, grabbing a parameter and viewing its default value is now easily performed with:

kwarg1 = params['kwarg1']
kwarg1.default # returns: None

similarly for the rest of the objects contained in parameters.


As for Python 2.x users, while inspect.getargspec isn’t deprecated, the language will soon be :-). The Signature class isn’t available in the 2.x series and won’t be. So you still need to work with inspect.getargspec.

As for transitioning between Python 2 and 3, if you have code that relies on the interface of getargspec in Python 2 and switching to signature in 3 is too difficult, you do have the valuable option of using inspect.getfullargspec. It offers a similar interface to getargspec (a single callable argument) in order to grab the arguments of a function while also handling some additional cases that getargspec doesn’t:

from inspect import getfullargspec

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

args = getfullargspec(someMethod)

As with getargspec, getfullargspec returns a NamedTuple which contains the arguments.

print(args)
FullArgSpec(args=['self', 'arg1', 'kwarg1'], varargs=None, varkw=None, defaults=(None,), kwonlyargs=[], kwonlydefaults=None, annotations={})

回答 1

import inspect
inspect.getargspec(someMethod)

参见检查模块

import inspect
inspect.getargspec(someMethod)

see the inspect module


回答 2

someMethod.func_code.co_argcount

或者,如果当前函数名称不确定,请执行以下操作:

import sys

sys._getframe().func_code.co_argcount
someMethod.func_code.co_argcount

or, if the current function name is undetermined:

import sys

sys._getframe().func_code.co_argcount

回答 3

inspect.getargspec()

获取函数参数的名称和默认值。返回包含四个内容的元组:(args,varargs,varkw,默认值)。args是参数名称的列表(它可能包含嵌套列表)。varargs和varkw是*和**参数的名称或无。defaults是默认参数值的元组;如果没有默认参数,则为None;如果该元组具有n个元素,则它们对应于args中列出的最后n个元素。

在2.6版中进行了更改:返回一个命名的元组ArgSpec(args,varargs,关键字,默认值)。

请参阅您可以列出关键字参数的python函数接收

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).

See can-you-list-the-keyword-arguments-a-python-function-receives.


回答 4

除此之外,我还看到大多数时候help()函数确实可以帮助您

例如,它提供了有关所采用参数的所有详细信息。

help(<method>)

给出以下

method(self, **kwargs) method of apiclient.discovery.Resource instance
Retrieves a report which is a collection of properties / statistics for a specific customer.

Args:
  date: string, Represents the date in yyyy-mm-dd format for which the data is to be fetched. (required)
  pageToken: string, Token to specify next page.
  parameters: string, Represents the application name, parameter name pairs to fetch in csv as app_name1:param_name1, app_name2:param_name2.

Returns:
  An object of the form:

    { # JSON template for a collection of usage reports.
    "nextPageToken": "A String", # Token for retrieving the next page
    "kind": "admin#reports#usageReports", # Th

Adding to the above, I’ve also seen that the most of the times help() function really helps

For eg, it gives all the details about the arguments it takes.

help(<method>)

gives the below

method(self, **kwargs) method of apiclient.discovery.Resource instance
Retrieves a report which is a collection of properties / statistics for a specific customer.

Args:
  date: string, Represents the date in yyyy-mm-dd format for which the data is to be fetched. (required)
  pageToken: string, Token to specify next page.
  parameters: string, Represents the application name, parameter name pairs to fetch in csv as app_name1:param_name1, app_name2:param_name2.

Returns:
  An object of the form:

    { # JSON template for a collection of usage reports.
    "nextPageToken": "A String", # Token for retrieving the next page
    "kind": "admin#reports#usageReports", # Th

回答 5

对于想要以可移植的方式在Python 2和Python 3.6+之间进行此操作的人们来说是个好消息:use inspect.getfullargspec()方法。它可以在Python 2.x和3.6+中使用

正如Jim Fasarakis Hilliard和其他人指出的那样,它以前是这样的:
1.在Python 2.x中:使用inspect.getargspec()
2.在Python 3.x中:使用签名,因为getargspec()getfullargspec()已弃用。

但是,从Python 3.6开始(受大众欢迎?),情况已经朝着更好的方向发展:

从Python 3 文档页面

inspect.getfullargspec(func)

在版本3.6中进行了更改:以前signature()在Python 3.5中记录了此方法的不推荐使用,但是为了恢复从原始getargspec()API 迁移来的单一源Python 2/3代码的明确支持的标准接口,该决定已被撤销。

Good news for folks who want to do this in a portable way between Python 2 and Python 3.6+: use inspect.getfullargspec() method. It works in both Python 2.x and 3.6+

As Jim Fasarakis Hilliard and others have pointed out, it used to be like this:
1. In Python 2.x: use inspect.getargspec()
2. In Python 3.x: use signature, as getargspec() and getfullargspec() were deprecated.

However, starting Python 3.6 (by popular demand?), things have changed towards better:

From the Python 3 documentation page:

inspect.getfullargspec(func)

Changed in version 3.6: This method was previously documented as deprecated in favour of signature() in Python 3.5, but that decision has been reversed in order to restore a clearly supported standard interface for single-source Python 2/3 code migrating away from the legacy getargspec() API.


回答 6

inspect.getargspec()满足您的需求

from inspect import getargspec

def func(a, b):
    pass
print len(getargspec(func).args)

inspect.getargspec() to meet your needs

from inspect import getargspec

def func(a, b):
    pass
print len(getargspec(func).args)

回答 7

正如其他答案所暗示的,getargspec只要被查询的东西实际上是一个功能,它就可以很好地工作。它不适用于,等内置函数openlen在以下情况下将引发异常:

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

以下功能(受此答案启发)展示了一种解决方法。它返回预期的args数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__字符串中解析出函数规范。显然,这依赖于所述字符串的格式,因此很难实现!

As other answers suggest, getargspec works well as long as the thing being queried is actually a function. It does not work for built-in functions such as open, len, etc, and will throw an exception in such cases:

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

The below function (inspired by this answer) demonstrates a workaround. It returns the number of args expected by 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

The idea is to parse the function spec out of the __doc__ string. Obviously this relies on the format of said string so is hardly robust!


回答 8

func.__code__.co_argcount给您任何数量的参数 之前 *args

func.__kwdefaults__给您关键字参数 之后的字典 *args

func.__code__.co_kwonlyargcount 等于 len(func.__kwdefaults__)

func.__defaults__为您提供出现在前面可选参数的值 *args

这是简单的例子:

>>> def a(b, c, d, e, f=1, g=3, h=None, *i, j=2, k=3, **L):
    pass

>>> a.__code__.co_argcount
7
>>> a.__defaults__
(1, 3, None)
>>> len(a.__defaults__)
3
>>> 
>>> 
>>> a.__kwdefaults__
{'j': 2, 'k': 3}
>>> len(a.__kwdefaults__)
2
>>> a.__code__.co_kwonlyargcount
2

func.__code__.co_argcount gives you number of any arguments BEFORE *args

func.__kwdefaults__ gives you a dict of the keyword arguments AFTER *args

func.__code__.co_kwonlyargcount is equal to len(func.__kwdefaults__)

func.__defaults__ gives you the values of optional arguments that appear before *args

Here is the simple illustration:

>>> def a(b, c, d, e, f=1, g=3, h=None, *i, j=2, k=3, **L):
    pass

>>> a.__code__.co_argcount
7
>>> a.__defaults__
(1, 3, None)
>>> len(a.__defaults__)
3
>>> 
>>> 
>>> a.__kwdefaults__
{'j': 2, 'k': 3}
>>> len(a.__kwdefaults__)
2
>>> a.__code__.co_kwonlyargcount
2

回答 9

在:

import inspect 

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

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

出:

4


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

对于3.5以下的python,您可能需要在上面的代码中替换inspect.getfullargspecinspect.getargspec

In:

import inspect 

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

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

Out:

4


Note: If xyz wasn’t inside class X and had no “self” and just “a, b, c”, then it would have printed 3.

For python below 3.5, you may want to replace inspect.getfullargspec by inspect.getargspec in the code above.