PyCharm 2025.2 Help

用于文档字符串的传统类型语法

PyCharm 支持在 Python 中使用文档字符串指定类型的传统方法。 在此过程中,支持的格式包括:

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

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 # 返回类型:'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年 9月 26日