You need to enable JavaScript to run this app. Python泛型函数类型标注:如何正确声明ACTION_DEFS与简化Prompter定义?
优惠活动
大模型
产品
解决方案
定价
更多

Python泛型函数类型标注:如何正确声明ACTION_DEFS与简化Prompter定义?

问题1:如何正确编写ACTION_DEFS的类型声明

你遇到的报错是因为全局声明的类型变量_T没有绑定外层泛型作用域,直接用于列表类型标注时无意义。根据你的使用场景,有两种解决方案:

场景A:列表可存储任意泛型参数的ActionDef,各元素类型独立

导入Any标注即可满足你存储任意泛型ActionDef的需求:

from typing import List, TypeVar, Callable, Any

_T = TypeVar('_T')
Prompter = Callable[[str, List[_T]], _T]
ActionDef = Callable[[Prompter[_T]], None]

# 正确标注,可存任意泛型参数的ActionDef
ACTION_DEFS: List[ActionDef[Any]] = []

场景B:列表内所有ActionDef共用同一个泛型参数

将列表封装到泛型类中,绑定类型变量的作用域即可:

from typing import List, TypeVar, Callable, Generic

_T = TypeVar('_T')
Prompter = Callable[[str, List[_T]], _T]
ActionDef = Callable[[Prompter[_T]], None]

class ActionRegistry(Generic[_T]):
    def __init__(self):
        # 该列表下所有ActionDef共用同一个泛型参数_T
        self.action_defs: List[ActionDef[_T]] = []
问题2:是否有办法定义Prompter,避免每次使用时都携带[_T]泛型参数

可以,分版本有不同的实现方案:

Python 3.12+

使用PEP 695引入的新泛型别名语法,写法更简洁,且Pylance等类型检查器可以自动根据上下文推断泛型参数,绝大多数场景下不需要显式标注参数:

from typing import Callable, List, Any

# 新泛型语法,无需单独声明TypeVar
type Prompter[T] = Callable[[str, List[T]], T]
type ActionDef[T] = Callable[[Prompter[T]], None]

# 使用时无需显式写泛型参数,类型自动推断
def sample_action(p: Prompter) -> None:
    # 传入int列表时,自动推断返回值为int
    select_res = p("请选择数字", [1, 2, 3])

Python 3.11及更低版本

搭配from __future__ import annotations使用,绝大多数使用场景下Pylance可以自动推断泛型类型,不需要显式携带[_T]参数,仅在需要显式约束类型的场景下再标注即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 15:24:02