通过文档字符串指定类型
简介
您一直在调试代码,现在在调试过程中,您还可以收集类型信息,并在文档字符串中指定这些类型。
PyCharm 提供了一项意图操作,使您能够在运行时收集类型信息,并定义类型说明。
不过,也可以在不使用调试器的情况下手动指定参数的类型。
这两种情况都在 示例 一节中进行说明。
文档字符串中的类型语法
以下示例在每种受支持的文档字符串格式中指定同一函数的参数类型和返回值类型。 PyCharm 会从文档字符串文本中识别格式。 如果无法识别格式,则使用在 集成工具 中选择的格式。
def area(width, height):
"""Calculate the area of a rectangle.
:param width: The width of the rectangle.
:type width: float
:param height: The height of the rectangle.
:type height: float
:return: The area of the rectangle.
:rtype: float
"""
return width * height
您还可以在参数描述所在的同一行指定其类型,例如 :param float width: The width of the rectangle.
def area(width, height):
"""Calculate the area of a rectangle.
Args:
width (float): The width of the rectangle.
height (float): The height of the rectangle.
Returns:
float: The area of the rectangle.
"""
return width * height
def area(width, height):
"""Calculate the area of a rectangle.
Parameters
----------
width : float
The width of the rectangle.
height : float
The height of the rectangle.
Returns
-------
float
The area of the rectangle.
"""
return width * height
指定类型
指定参数类型
按 Ctrl+Alt+S ,然后转到 。
选择 在文档注释存根中插入类型占位符 复选框。
将插入符号置于函数名处,然后按下 Alt+Enter。
在打开的意图操作列表中,选择 插入文档字符串存根。 PyCharm 会根据所选的文档字符串格式,使用在调试器会话期间收集的类型说明,创建文档字符串存根。
指定返回类型
您还可以为函数的返回内容编写文档。 PyCharm 将生成 :return: 和 :rtype: 部分(或其在所选文档字符串格式中的等效内容)。
将插入符号置于函数名处,然后按下 Alt+Enter。
在打开的意图操作列表中,选择 在文档字符串中指定返回类型。

示例
请查看以下代码:
import math
class SimpleEquation:
def demo(self, a, b, c):
d = math.sqrt(abs(b ** 2 - 4 * a * c))
root1 = (-b + d) / (2 * a)
root2 = (-b - d) / (2 * a)
return root1, root2
SimpleEquation().demo(3, 2, 1)
手动指定类型
请注意,对于 reStructuredText ,可以使用两种格式来指定类型:
:param param_type param_name: parameter description(类型说明与参数说明在同一行。):type param_name: param_type(类型说明位于单独一行)
下面显示了这两种写法:

借助调试器指定类型
2026年 11月 3日




