Python、Google 风格的文档字符串:将参数或返回类型定义为另一种类型的子类?

问题描述

应该如何使用 Google 样式的文档字符串记录参数或返回类型旨在成为特定类型的子类?

这是我在使用类型提示时建议子类的方式。

from typing import TYPE_CHECKING,Type
...

if TYPE_CHECKING:
    from package.core import AbstractClass

def foo(bar: Type["AbstractClass"]) -> str:
    ...

假设以上是合理的,那么我如何在文档字符串中类似地记录它?

def foo(bar: Type["AbstractClass"]) -> str:
    """Map the class to str for no other reason then that SO question makes more sense.

    Args:
        bar (???): A concrete subclass of an abstract class.

    Returns:
        str: ...
    """
    ...

解决方法

我建议不要重复文档字符串中的类型信息。您提到您使用了 pdoc,它已经显示了类型注释,因此您在此处创建了不必要的不​​一致来源。

如果你真的想重复类型信息,你可以重复你用于注释的内容,即Type[AbstractClass]