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

Python3中如何为返回函数的函数添加类型标注?

正确的类型标注方式

你不能用function[int, int]这种写法,在Python的类型标注体系里,要明确描述返回函数的参数与返回值类型,需要用到Callable类型(Python 3.9及以上可直接使用标准库版本,低版本需从typing模块导入)。

方法一:使用typing.Callable(兼容Python 3.5+)

修改后的代码如下:

from typing import Callable

def fnA(x: int, y: int) -> Callable[[int], int]:
    def fnB(z: int) -> int:
        return x + y + z  # 注:原代码未使用参数z,修正后才符合调用`fnA(3,4)(5)`返回12的逻辑
    return fnB
  • Callable[[int], int]的含义是:接受一个int类型参数、返回int类型结果的函数。方括号内的列表是参数类型集合,最后一个元素是返回值类型。

方法二:Python 3.9+ 简化写法

Python 3.9开始,Callable被整合到标准库的collections.abc模块,无需再导入typing:

from collections.abc import Callable

def fnA(x: int, y: int) -> Callable[[int], int]:
    def fnB(z: int) -> int:
        return x + y + z
    return fnB

更具可读性的复用方式:用Protocol定义函数类型

如果该函数类型需要多次复用,可通过typing.Protocol(Python 3.8+支持)定义一个清晰的协议类:

from typing import Protocol

class SingleIntArgFunc(Protocol):
    def __call__(self, z: int) -> int:
        ...

def fnA(x: int, y: int) -> SingleIntArgFunc:
    def fnB(z: int) -> int:
        return x + y + z
    return fnB

这种方式能让函数类型的含义更直观,尤其适合复杂或高频使用的函数类型场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:06:44