缩短Sphinx中Python类型注释的显示格式

sch*_*ard 5 python type-hinting python-sphinx autodoc

鉴于模块中的以下函数,mymodule我想使用 Sphinx 进行记录autodoc

\n
from typing import Union\nfrom collections.abc import Iterable\nfrom numpy.typing import ArrayLike\n\ndef foo(a: Union[str, int], b: Iterable, c: ArrayLike) -> None:\n    """Do something useful."""\n    pass\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
\n

khadl._util.foo(a:Union [str,int],b:collections.abc.Iterable,c:Union [int,float,complex,str,字节,numpy.generic,Sequence [Union [int,float,complex] , str, bytes, numpy.generic]], 序列[序列[任意]], numpy.typing._array_like._SupportsArray]) \xe2\x86\x92 无

\n
\n

这是不可读的。源自模块的类typing以简短形式显示(Union, Sequence, Any),但对于抽象基类,Iterable会生成唯一标识符(collections.abc.Iterable),ArrayLike甚至“解包”(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])。

\n

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

\n

sch*_*ard 10

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

from __future__ import annotations
Run Code Online (Sandbox Code Playgroud)

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

autodoc_type_aliases = {
    'Iterable': 'Iterable',
    'ArrayLike': 'ArrayLike',
}
Run Code Online (Sandbox Code Playgroud)

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