sphinx autodoc扩展的类型提示(pep 484)支持

sphinx-autodoc-typehints的Python项目详细描述


此扩展允许您使用Python3注释来记录可接受的参数类型 函数的返回值类型。这允许您以非常自然的方式使用类型提示, 允许您从此处迁移:

defformat_unit(value,unit):"""
    Formats the given value as a human readable string using the given units.

    :param float|int value: a numeric value
    :param str unit: the unit for the value (kg, m, etc.)
    :rtype: str
    """return'{} {}'.format(value,unit)

对此:

fromtypingimportUniondefformat_unit(value:Union[float,int],unit:str)->str:"""
    Formats the given value as a human readable string using the given units.

    :param value: a numeric value
    :param unit: the unit for the value (kg, m, etc.)
    """return'{} {}'.format(value,unit)

安装和设置

首先,使用pip下载并安装扩展:

$ pip install sphinx-autodoc-typehints

然后,将扩展名添加到conf.py

extensions=['sphinx.ext.autodoc','sphinx_autodoc_typehints']

选项

接受以下配置选项:

  • set_type_checking_flag(默认值:False):如果True,则将typing.TYPE_CHECKING设置为 True启用“昂贵的”输入导入
  • typehints_fully_qualified(默认值:False):如果True,则类名始终是完整的 合格(例如module.for.Class)。如果False,则只显示类名(例如 Class

工作原理

扩展监听autodoc-process-signatureautodoc-process-docstring 斯芬克斯事件。在前者中,它从函数签名中剥离注释。在后者中, 它将适当的:type argname::rtype:指令注入docstring。

只有DOCSTATE中存在一个现有的{TT1717}指令的参数得到它们各自的 :type:指令已添加。当且仅当不存在时,添加{TT16} $指令 ^找到{tt16}$。

与sphinx.ext.napoleon兼容

要对sphinx autodoc类型提示使用sphinx.ext.napoleon,请确保加载 sphinx.ext.napoleon首先,sphinx autodoc typehints之前。关于这个问题见Issue 15 追踪器了解更多信息。

处理循环导入

有时,来自两个不同模块的函数或类需要在它们的 键入批注。这会产生循环导入问题。解决方法如下:

  1. 只导入模块,不导入其中的类/函数
  2. 在类型注释中使用前向引用(例如 def methodname(self, param1: 'othermodule.OtherClass'):

在python 3.7上,甚至可以使用from __future__ import annotations并删除引号。

使用类型提示注释

如果要编写与Python2.7兼容的代码,则不能使用常规的 键入批注。相反,您必须安装typed_ast,并在 以下方式:

defmyfunction(arg1,# type: intarg2# type: str)# type: (...) -> intreturn42

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java如何在Spring Boot 2.2.0中添加弹性搜索?   jakarta ee如何在没有java认证的情况下停止直接访问网页(自定义标记)   java Hibernate:使用executeUpdate()的批删除未清除一级缓存   java如何在Hibernate中插入外键定义为Long的实体?   带参数的java Mockito单元测试计算器方法   java如何从Rally Rest API读取集合属性   java如何对基于消息的处理执行集成测试?   带插入排序的java排序字符串数组标记,双链表   java为什么在基于注释的Spring app@Value默认值中解析为null?   java Apache Commons Http客户端注册特定于客户端的协议   如何使用java反转字符串中n个部分的n个字符   java Tomcat在本地主机上运行良好,但在部署时出现内部服务器错误   使用信号量的变量的java结果   Java编译/运行时类路径问题   java哪个提供商负责AES/CTR/NOP添加?   伪错误解码器中的java响应未获取Zalando问题自定义属性