【问题标题】:Shorten display format of Python type annotations in Sphinx缩短 Sphinx 中 Python 类型注释的显示格式
【发布时间】:2021-08-01 00:45:27
【问题描述】:

给定一个名为 mymodule 的模块中的以下函数,我想使用带有 autodoc 的 Sphinx 进行记录:

from typing import Union
from collections.abc import Iterable
from numpy.typing import ArrayLike

def foo(a: Union[str, int], b: Iterable, c: ArrayLike) -> None:
    """Do something useful."""
    pass

在源代码中,函数的签名非常易读。但是,在autodoc 生成的文档中,签名显示为

khadl._util.foo(a: Union[str, int], b: collections.abc.Iterable, c: Union[int, float, complex, str, bytes, numpy.generic, Sequence[Union[int, float, complex, str, bytes, numpy.generic]], Sequence[Sequence[Any]], numpy.typing._array_like._SupportsArray]) → None

这是不可读的。源自typing 模块的类以简短形式显示(UnionSequenceAny),但对于抽象基类Iterable,会生成一个唯一标识符(collections.abc.Iterable)和@ 987654332@ 甚至被“解包”(Union[int, float, complex, str, bytes, numpy.generic, Sequence[Union[int, float, complex, str, bytes, numpy.generic]], Sequence[Sequence[Any]], numpy.typing._array_like._SupportsArray])。

如何配置 Sphinx 以便函数的签名在文档中以可读的方式显示,例如和源代码一样?

【问题讨论】:

  • 您的c 输入非常笼统。必须有那么多选择吗?
  • 您可以通过将签名添加为文档字符串的第一行来完成此操作。见stackoverflow.com/q/12082570/407651
  • @astrochun 好吧,我不只是为了好玩才选择那种类型。它是“任何可以转换为numpy.ndarray 的东西”。
  • 嗯。它不包括可转换为numpy.ndarraylist
  • @astrochun lists 是 Sequences。

标签: python python-sphinx type-hinting autodoc


【解决方案1】:

经过一番挖掘,我发现autodoc_type_aliases 选项可用于实现此目的。为了让它发挥作用,你必须说

from __future__ import annotations

在您正在记录的模块的开头。 (这会激活 PEP563 中所述的延迟评估注释,这将成为 Python 3.10 中的标准。) 然后,您可以告诉 Sphinx 如何打印 conf.py 文件中的注释。

autodoc_type_aliases = {
    'Iterable': 'Iterable',
    'ArrayLike': 'ArrayLike'
}

(每个条目的键是源中写入的类型提示,值是它在生成的文档中的写入方式。)

【讨论】:

    猜你喜欢
    • 2021-09-05
    • 2018-11-07
    • 2017-02-25
    • 2015-04-18
    • 2014-06-30
    • 2017-10-10
    • 1970-01-01
    • 2020-04-08
    • 2020-06-06
    相关资源
    最近更新 更多