在支持sphinx的docstring中使用python 3注释
sphinx-autodoc-annotation的Python项目详细描述
在启用sphinx的docstrings中使用python 3注释
如果您使用python 3并编写支持sphinx的docstring,那么您可能会想 键入:type arg:或:rtype:指令时不需要执行的工作。毕竟,为什么不使用 这个的注释?
当然,:param str arg: description不是很多工作,但是当您想要记录 参数作为具有:class:链接的特定类,则需要使用:type: 而且很麻烦。通过使用此狮身人面像扩展,您可以将其旋转:
def f(a): """Do something. :param a: description for a :type a: :class:`ClassForA` :rtype: str """
进入:
def f(a: ClassForA) -> str: """Do something. :param a: description for a """
安装
首先,您需要python 3.3+和sphinx文档(启用autodoc)。
您可以使用以下命令安装sphinx-autodoc-annotation:
$ pip install sphinx-autodoc-annotation
然后,您需要在conf.py文件中启用它:
extensions = [ 'sphinx.ext.autodoc', 'sphinx_autodoc_annotation', ]
你完了!
用法
使用这个扩展所需要做的就是用 参数和返回值需要类型。:type:和:rtype:指令将 自动添加到docstring中。
这些指令的行为类似于手动添加它们,也就是说,您的参数不会 只出现在:type arg:youneed:param arg:to be there(带有 是的)让你的类型出现。
当没有注释时,参数类型是从默认值推导出来的。如果您的默认值 是一个bool、str、int或float,将考虑该类型的参数。 这个特性之所以存在,主要是因为f(flag: bool = False)觉得有点多余。
在所有情况下,docstring中的:type:和:rtype:指令始终具有优先权 超过注释和默认值。