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-signature和autodoc-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 追踪器了解更多信息。
处理循环导入
有时,来自两个不同模块的函数或类需要在它们的 键入批注。这会产生循环导入问题。解决方法如下:
- 只导入模块,不导入其中的类/函数
- 在类型注释中使用前向引用(例如 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