python - 计算函数签名中的位置参数

标签 python python-3.x

我有以下函数签名:

# my signature
def myfunction(x, s, c=None, d=None):
    # some irrelevant function body

我需要位置参数的数量。如何返回位置参数 (x & s) 的数量 (2)。关键字参数的数量无关紧要。

最佳答案

可以得到所有参数的个数(使用f.__code__.co_argcount),关键字参数的个数(使用f.__defaults__),然后减去后者从一开始:

def myfunction(x, s, c=None, d=None):
  pass

all_args = myfunction.__code__.co_argcount

if myfunction.__defaults__ is not None:  #  in case there are no kwargs
  kwargs = len(myfunction.__defaults__)
else:
  kwargs = 0

print(all_args - kwargs)

输出:

2

来自Docs :

__defaults__: A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value.

和:

co_argcount is the number of positional arguments (including arguments with default values);

关于python - 计算函数签名中的位置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57885922/

相关文章:

带有生成器的 Python 嵌套循环不起作用(在某些情况下)?

python - Docker 中的 Elasticsearch : elasticsearch. 异常。ConnectionError:ConnectionError - Python

python - ConfigParser 从空值中删除引号

python - Python 类型提示语法如何/为什么起作用?

python - 在matplotlib中为起点和终点赋予不同的颜色

python - 为什么 python 日志记录模块使用旧的字符串格式?

python - 是否可以从 Flutter 应用程序运行 Python 方法?

python - 恢复保存的模型后如何获取/打印张量值?

python - `np.nanargmin([np.nan, np.inf]) = 0`背后的逻辑

python - 如何在 celery 任务执行时停止它并在一段时间后继续执行?