python:如何同时使用类型注释和文档字符串格式

问题描述 投票:0回答:1

现在我们在 Python 中有了类型注释,我想知道如何使用类型注释和文档字符串格式来记录代码。

具体来说,在文档字符串中将参数类型指定为注释和

:type:
似乎是多余的,如下面的重构文本格式示例所示。文档字符串格式的描述仍然有用。


def my_function(db: Session, name: str) -> str:
   """Some function

   :param db: a database connection
   :type db: Session
   :param name: some name
   :type name: str
   :return: return something
   :rtype: str
   """

一种选择可能是像这样编写函数:


def my_function(db: Session, name: str) -> str:
   """Some function

   :param db: a database connection
   :param name: some name
   :return: return something
   """

如何为带有类型注释的代码编写 DRY 文档字符串,以便它与 IDE 类型推断工具(即 VSCode)、linter、mypy、自动文档工具(即 Sphynx)以及其他基于社区的用于生成和生成文档的工具最兼容反思文档?

python python-3.x annotations python-typing docstring
1个回答
0
投票

只需使用函数签名即可。也不要记录下来。

任何有价值的文档工具都会解析函数签名(包括类型)并显示这一点,因此

:type foo:
确实是多余的。

对于 sphinx,请参阅 autodoc 扩展,尤其是这里

© www.soinside.com 2019 - 2024. All rights reserved.