type
语句。如何正确记录类型别名?
我尝试过:
type Number = int | float
"""Represents a scalar number that is either an integer or float"""
但这似乎并没有将文档字符串与别名关联起来。我尝试将文档字符串放在
=
之后和别名定义之前,但这会产生错误。
我认为没有直接的方法。对于类、函数和方法,如果第一个语句是字符串,则该字符串将添加到类/方法/函数的
__doc__
属性中。
举个例子:
def foo():
"Docstring"
运行时与:
相同def foo():
pass
foo.__doc__ = "Docstring"
因为 TypeAliasType 定义缺少隐式
__doc__
设置。我已经尝试过明确地做到这一点。
type Number = int | float
Number.__doc__ = "Docstring"
这会导致以下错误:
AttributeError: 'typing.TypeAliasType' object attribute '__doc__' is read-only
所以我认为没有支持的 TypeAliasType 实例文档方式。这取决于您的文档生成工具,例如PyCharm 或 sphinx。 以及他们的静态代码分析。文档字符串是否“相关”。