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 HashMap线程安全性   java Android:从sqlite数据库检索数据   java OpeNni:颜色坐标到深度坐标   替换Java将所有逗号替换为分号,引号内的逗号除外   java如何获取数据库中的图像,并将其设置为特定行的表的“tooltipText()   java如何使用“没有休息吗?   java Spring引导与Gradle版本的Gradle问题   java无法更新oracle中的clob字段   用Java创建一个简单的银行账户   java openfire服务器是否实现了地雷功能?   java Android获取支持的区域设置列表   用sqlite安卓实现java简单数学计算   JavaAEMServlet获取请求头值   在java中生成随机16位数字   有类似dotnetkicks的东西吗。com for Java   xml@xmlanyement不会解组为特定的Java类型,而是在JAXBElement处停止   尝试反序列化对象时发生java错误   java如何将JSON对象从POSTMAN发送到Restful Web服务   com的java性能。太阳网httpserver。HttpServer和HttpURLConnection?