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

Python 3.10中Protocol自引用类型提示的前置声明方法问询

问题:Python 3.10中为Protocol内部方法参数添加自身类型提示的问题

我尝试编写如下泛型类型代码:

from typing import Sequence, TypeVar, Hashable, Protocol, NoReturn


class _SortHashable(Protocol, Hashable):
    def __lt__(self, other) -> bool:
        ...

    def __eq__(self, other) -> bool:
        ...


SortHashableT = TypeVar("SortHashableT", bound=_SortHashable)

def foo(sequence: Sequence[SortHashableT]) -> NoReturn:
    ...

为给other对象添加类型提示,我尝试修改为:

class _SortHashable(Protocol, Hashable):
    def __lt__(self, other: _SortHashable) -> bool:
        ...

但编辑器报错,推测该写法不被支持。请问是否有类似C++的前置声明方式实现?我使用的是Python 3.10。

解决方案

在Python类型提示体系中,对于尚未完成定义的类或Protocol,可以使用字符串字面量形式的前向引用来解决这个问题,Python 3.10原生支持这种写法,无需额外导入兼容模块。

修改后的正确代码如下:

from typing import Sequence, TypeVar, Hashable, Protocol, NoReturn


class _SortHashable(Protocol, Hashable):
    def __lt__(self, other: "_SortHashable") -> bool:
        ...

    def __eq__(self, other: "_SortHashable") -> bool:
        ...


SortHashableT = TypeVar("SortHashableT", bound=_SortHashable)

def foo(sequence: Sequence[SortHashableT]) -> NoReturn:
    ...

原理是:当定义_SortHashable时,该类还未完成初始化,直接使用标识符_SortHashable会触发名称未定义的错误;而字符串形式的引用会让类型检查器延迟解析这个名称,直到整个类定义完成,这就相当于实现了类似C++前置声明的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 13:07:16