在文档字符串中使用输入模块

dam*_*amd 3 python docstring typing pycharm

假设我有一个带有文档字符串的函数,其中我将返回类型声明为带有两个字符串的元组:

def foo():
    """
    Returns:
        Tuple[str, str]: Tuple of first name and last name
    """
Run Code Online (Sandbox Code Playgroud)

如果我不在文档字符串之外的任何地方使用它,Tuple我是否应该导入它?typing

Mar*_*ers 5

PyCharm 对类型提示的文档字符串支持实际上并未使用typing. 您不需要导入该模块。

typing模块仅用于支持注释在运行时执行的事实;对于以 开头的语句def foo() -> Tuple[str, str]:,Python 实际上会计算表达式Tuple[str, str],因此期望能够解析名称。(从 Python 3.7 开始,您可以使用 禁用(或者更确切地说,推迟)评估from __future__ import annotations)。

但是文档字符串通常不会被评估,并且不应该包含可运行的 Python 代码。

除非您有硬性要求将类型信息放入文档字符串中,否则我会坚持使用实际注释

from typing import Tuple


# type aliases
firstname = str
lastname = str


def foo() -> Tuple[firstname, lastname]:
    """Descriptive line documenting this function's purpose"""
    # ...
Run Code Online (Sandbox Code Playgroud)