PyCharm 2025.3 Help

文档字符串的旧版类型语法

PyCharm 支持使用文档字符串在 Python 中指定类型的旧版方法。 在这种情况下,支持的格式有:

要选择所需的文档字符串格式,请使用设置对话框中的 Python 集成工具 页面。

Python 文档字符串中的类型语法未由任何标准定义。 因此,PyCharm 建议使用以下表示法:

语法

说明

Foo

当前作用域中可见的类 Foo

x.y.Bar

来自 x.y 模块的类 Bar

Foo | Bar

Foo 或 Bar

(Foo, Bar)

Foo 和 Bar 的元组

list[Foo]

Foo 元素的列表

dict[Foo, Bar]

从 Foo 到 Bar 的字典

T

泛型类型(T-Z 保留用于泛型)

T <= Foo

上界为 Foo 的泛型类型

Foo[T]

使用 T 参数化的 Foo

(Foo, Bar) -> Baz

以 Foo 和 Bar 为参数并返回 Baz 的函数

list[dict[str, datetime]]

从 str 到 datetime 的字典列表(嵌套参数)

指定局部变量的类型

请考虑使用 :type@type 文档字符串添加有关局部变量期望类型的信息:

局部变量的类型提示

您也可以使用 isinstance 定义局部变量的期望类型:

局部变量的类型提示

指定字段的类型

您可以使用类型提示来指定字段的期望类型:

字段的类型提示

或者,您可以在类的文档字符串中指定字段的类型:

类属性的类型提示

指定返回类型

使用文档字符串 :rtype@rtype 指定期望的返回类型:

py_type_hinting_return2
  • :rtype: collections.Iterable[int] # return type :'items' 的类型为 generatorcollections.Iterable ,'a' 的类型为 int ,请参见以下代码:

    def my_iter(): global i for i in range(10): yield i items = my_iter() for a in items: print a
  • :rtype: list[int] for my_iter # return type: 'a' 的类型为 int ,请参见以下代码:

    def my_iter(): for i in range(10): yield i for a in my_iter(): print a

指定参数类型

请考虑添加有关期望参数类型的信息。 此信息使用文档字符串进行指定。 您可以根据所选的文档字符串格式使用不同的文档字符串,例如 :type@typeArgs。 使用项目设置更改文档字符串格式(文件 | 设置 | Python | 集成工具)。

使用文档字符串定义参数类型(:type)
使用文档字符串定义参数类型(Args)
最后修改日期: 2025年 12月 2日