You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在reST文档字符串中指定可调用参数的返回类型?

在reStructuredText文档字符串中标注Callable类型的返回值

问题背景

使用Python类型提示时,我们可以通过Callable[[int, str], bool]明确标注一个接受int和str类型参数、返回bool类型的函数参数,示例代码如下:

from typing import Callable

def func(another_func: Callable[[int, str], bool]):
    pass

但在reStructuredText(reST)格式的文档字符串中,尝试用function[[int, str], bool]的写法标注返回值时无法生效,目前仅能写出类似:param function[int, str] another_func:的不完整形式。

环境信息:

  • PyCharm 2021.2.4 x64
  • Python 3.9

解决方案

在reST文档字符串中,需要使用标准的typing.Callable语法来完整标注函数类型(包括返回值),具体有两种可行写法:

写法1:导入Callable后使用

from typing import Callable

def func2(another_func):
    """
    :param another_func: 接受int和str参数并返回bool类型的函数
    :type another_func: Callable[[int, str], bool]
    """
    pass

写法2:使用字符串形式的完整类型路径(无需提前导入)

Python 3.9+支持字符串形式的类型提示,因此可以直接写出完整的类型路径:

def func2(another_func):
    """
    :param another_func: 接受int和str参数并返回bool类型的函数
    :type another_func: typing.Callable[[int, str], bool]
    """
    pass

PyCharm的reST文档字符串解析器支持标准的typing类型语法,因此直接使用Callable的规范写法即可被正确识别,无需使用非标准的function关键字。

内容的提问来源于stack exchange,提问作者Mandera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:24:12