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

能否使用typing_extensions的实验性类型?Self类型使用报错咨询

报错原因
  • typing_extensions.Self 本质是为静态类型检查工具设计的类型占位符,Python 3.8 并未内置对 PEP 673 规范的运行时支持,运行时无法识别 Self 这个未绑定的占位符类型。
  • 在类定义阶段直接将 Self 作为 typing.List 的泛型参数传入时,Python 解释器会立刻对泛型参数做运行时校验,此时 Self 还未和正在定义的 MenuItem 类完成绑定,就会抛出对应的类型错误。
可行解决方案
  • 方案1:使用前向引用字符串写法
    直接将类型写为 typing.List["MenuItem"] 即可,Python 3.7 及以上版本都支持该写法,运行时不会报错,静态类型检查器也可以正常识别对应的类型。
  • 方案2:开启延迟注解求值
    在当前 Python 文件的第一行添加 from __future__ import annotations 语句,该语句会让 Python 解释器将所有类型注解都以字符串形式存储,不会在类定义阶段做运行时求值,此时可以正常使用 typing.List[typing_extensions.Self] 写法,静态类型检查器依然可以正常解析类型。
  • 方案3:使用绑定了当前类的 TypeVar 替代
    代码示例如下:
import dataclasses
import typing
from typing import TypeVar

T = TypeVar("T", bound="MenuItem")

@dataclasses.dataclass
class MenuItem:
    url: str
    title: str
    description: str = ""
    items: typing.List[T] = dataclasses.field(default_factory=list)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:15:03