python - 以编程方式获取 python 函数参数的描述

标签 python arguments

假设我有以下功能:

def get_fullname(first: str, last: str = "Miller"):
    """
    :param first: First name
    :param last: Last name
    :return: Fullname
    """
    return f"{first} {last}"

我知道我可以使用 inspect 模块获得有关函数的大量信息:

import inspect
spec = inspect.getfullargspec(get_fullname)
print(spec)
# FullArgSpec(args=['first', 'last'], varargs=None, varkw=None, defaults=('Miller',), kwonlyargs=[], kwonlydefaults=None, annotations={'first': <class 'str'>, 'last': <class 'str'>})

我是否可以通过编程方式获取这些参数的描述?看起来不可能,但只是确定一下。看起来这是 specifying types 的 PyCharm 方式.

最佳答案

您可以安装和使用docstring_parser :

import docstring_parser

def get_fullname(first: str, last: str = "Miller"):
    """
    :param first: First name
    :param last: Last name
    :return: Fullname
    """
    return f"{first} {last}"

doc = docstring_parser.parse(get_fullname.__doc__)
for param in doc.params:
    print(param.arg_name, param.description)
print(doc.returns.description)

这个输出:

first First name
last Last name
Fullname

关于python - 以编程方式获取 python 函数参数的描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55642672/

相关文章:

python - django - 从一个文件调用函数到另一个文件

python - 更新奇怪的字典列表中的值

python - 使用 imgaug 创建和保存增强图像时遇到问题

python - 如何将表示 Bash 命令元素的列表元素组合到具有等于符号的新列表中

c++ - 指向参数减少的函数的指针

python - 声明一个带有数组参数的python函数并将一个数组参数传递给函数调用?

python - Pandas 错误 : Index contains duplicate entries, 无法 reshape

python - 如何运行 python 函数

带有打印函数结果的 Python sys.argv TypeErrors?

python - 遍历 *args?