没有项目描述
sphinx-autodoc-future-annotations的Python项目详细描述
此扩展允许您使用Python 3类型注释来记录模块和类属性,以及 函数参数和返回类型。 扩展还支持由于类型注释而需要的循环导入。 扩展只适用于Python 3.7及更高版本,需要使用from __future__ import annotations
示例(a_module.py):
from__future__importannotationsimporttypingastift.TYPE_CHECKING:importanother_modulemodule_attribute:t.Optional[another_module.SomeClass]=None'''An attribute of the module.'''classAClass:'''A class.'''instance_attribute:int'''An instance attribute.'''class_attribute:float=3.0'''A class attribute.'''def__init__(self,arg:t.Union[int,str]):passdefmethod(self)->int:'''A method.'''pass
示例(another_module.py):
from__future__importannotationsimporttypingiftyping.TYPE_CHECKING:importa_moduledeffunction(arg:a_module.AClass):'''A function.'''passclassSomeClass:pass
安装和设置
首先,使用pip下载并安装扩展:
$ pip install sphinx_autodoc_future_annotations
然后,将扩展名添加到您的conf.py:
extensions=['sphinx.ext.autodoc','sphinx_autodoc_future_annotations',]
工作原理
以下方式支持由于类型注释而需要的循环导入。 首先,在导入模块时,钩子被猴子修补到sphinx.ext.autodoc中以执行操作。 这个钩子首先正常地导入模块。 然后它解析模块的代码,并找到任何顶层的if-语句,这些语句的条件是 TYPE_CHECKING来自typing模块。 此类if-语句中的所有语句都在te模块的上下文中执行。 这使附加导入可用于typing.get_type_hints。
扩展监听autodoc-process-signature和autodoc-process-docstring 斯芬克斯事件在前者中,它从函数签名中剥离注释。在后者中, 它将适当的:type argname:和:rtype:指令注入docstring。
当{ T{13} $和^ {tT14} $指令时,仅当且仅当未找到现有匹配指令时才添加。 如果找不到匹配的指令,则添加空的:param argname:指令。 这样就可以记录参数的类型,而不必在使用时添加琐碎的文档。
此扩展当前没有任何配置选项。
有些代码改编自sphinx-autodoc-typehints。
与sphinx.ext.napoleon兼容
要将sphinx.ext.napoleon与sphinx_autodoc_future_注释一起使用,请确保加载 sphinx.ext.napoleon首先,在sphinx_autodoc_future_注释之前
extensions=['sphinx.ext.autodoc','sphinx.ext.napoleon','sphinx_autodoc_future_annotations',]