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

Enum的@property方法返回类型Self在VS Code中触发Pylance错误

问题:Enum中使用Self类型注解导致Pylance报错

代码示例

from enum import Enum
from typing import Self

class Letter(Enum):
    A = "A"
    B = "B"
    C = "C"

    @property
    def neighbors(self) -> list[Self]:
        match self:
            case self.A:
                return [self.B]
            case self.B:
                return [self.A, self.C]
            case self.C:
                return [self.B]
            case _:
                raise ValueError

print(Letter.A.neighbors)
print(type(Letter.A.neighbors))

错误提示

Pylance Error: Expression cannot be assigned to return type ...

代码可正常运行,请问是代码、Pylance还是Visual Studio Code存在问题?如何消除该错误提示?


解答

这是Pylance的类型推断限制问题,代码本身逻辑没问题,VS Code只是搭载了Pylance插件,核心问题出在Pylance对Enum类中Self类型的处理不够完善。

消除错误提示的方法:

  • 方案1:用类名代替Self(推荐)
    把返回类型注解从list[Self]改成list["Letter"](用字符串包裹类名避免前置引用问题),Pylance就能正确识别枚举成员的类型了。修改后的代码:

    from enum import Enum
    
    class Letter(Enum):
        A = "A"
        B = "B"
        C = "C"
    
        @property
        def neighbors(self) -> list["Letter"]:
            match self:
                case self.A:
                    return [self.B]
                case self.B:
                    return [self.A, self.C]
                case self.C:
                    return [self.B]
                case _:
                    raise ValueError
    
    print(Letter.A.neighbors)
    print(type(Letter.A.neighbors))
    
  • 方案2:降低Pylance类型检查严格度
    在VS Code设置中,将python.analysis.typeCheckingMode从strict调整为basic或off。但这会削弱整体的类型检查能力,仅适合临时规避问题。

  • 方案3:升级Pylance插件
    检查VS Code中的Pylance插件是否为最新版本,后续版本可能修复了Self类型在Enum中的识别缺陷。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 06:26:02