我如何才能找到一个Python函数的参数的数量?我需要知道它有多少普通参数和多少命名参数。
例子:
def someMethod(self, arg1, kwarg1=None):
pass
这个方法有2个参数和1个命名参数。
我如何才能找到一个Python函数的参数的数量?我需要知道它有多少普通参数和多少命名参数。
例子:
def someMethod(self, arg1, kwarg1=None):
pass
这个方法有2个参数和1个命名参数。
当前回答
你可以通过(将"function"替换为你的函数名)获得参数的数量:
function.__code__.co_argcount ## 2
参数的名称为:
function.__code__.co_varnames ## ('a', 'b')
其他回答
Inspect.getargspec()来满足您的需求
from inspect import getargspec
def func(a, b):
pass
print len(getargspec(func).args)
正如其他答案所暗示的那样,只要查询的东西实际上是一个函数,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模块
这是获取函数的强制参数数量的解决方案(*)
如果使用了一些不常见的参数规范(具有默认值的仅限位置参数,没有默认值的仅限关键字参数,等等),那么本文提出的许多解决方案都无法实现这一目的。
from typing import Callable, Any
import inspect
def get_mandatory_argcount(f: Callable[..., Any]) -> int:
"""Get the number of mandatory arguments of a function."""
sig = inspect.signature(f)
def parameter_is_mandatory(p: inspect.Parameter) -> bool:
return p.default is inspect.Parameter.empty and p.kind not in (
inspect.Parameter.VAR_POSITIONAL,
inspect.Parameter.VAR_KEYWORD,
)
return sum(parameter_is_mandatory(p) for p in sig.parameters.values())
# mandatory keyword-only
def f1(b=2, *args, c, d=1, **kwds): pass
print(get_mandatory_argcount(f1))
# positional only with default
def f2(a=1, /, b=3, *args, **kwargs): pass
print(get_mandatory_argcount(f2))
(*)我想把这个作为一个答案,以编程方式确定一个函数所需的参数数量- 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).
看到can-you-list-the-keyword-arguments-a-python-function-receives。