python / python/mypy

`ClassVar` cannot contain `Self` type in generic classes

未关闭
#20,331 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

bug
主要语言
Python
星标
20.6k
派生
3.3k
PR 合并指标
PR 指标待抓取

描述

This rule seems correct when Self appears in a covariant position, like

class MyGeneric[T]:
    # ill-defined, what's the type of MySequence.example?
    example: ClassVar[Self]  # error: ClassVar cannot contain Self type in generic classes

However, if Self appears in a contravariant position, I do not see why this should be an error.

class MyGeneric[T]:
    pre_method_hooks: ClassVar[list[ Callable[[Self], None] ]] = []

Full example: https://mypy-play.net/?mypy=master&python=3.12&gist=951d5b3a168378cd33d9fc4aebd4572e

from typing import Callable, ClassVar, Self, Any
from abc import abstractmethod

class Transform[X, Y]:
    pre_transform_hooks: ClassVar[list[Callable[[Self], None]]] = []  # ❌️

    def __init_subclass__(cls) -> None:
        super().__init_subclass__()
        original_transform = cls.transform

        def wrapped_transform(self: Self, x: X, /, *args: Any, **kwargs: Any) -> Y:
            for hook in cls.pre_transform_hooks:
                hook(self)
            return original_transform(self, x, *args, **kwargs)
        cls.transform = wrapped_transform  # type: ignore[method-assign]

    @abstractmethod
    def transform(self, x: X, /) -> Y: ...

class Demo(Transform[int, int]):
    def transform(self, x: int, /) -> int: return 0

    def hello_world(self) -> None:
        print(f"Hello, world! from {self}")

    pre_transform_hooks: ClassVar[list[Callable]] = [hello_world]

Demo().transform(0)  # prints "Hello, world! from <__main__.Demo object at ...>"
main.py:5: error: ClassVar cannot contain Self type in generic classes  [misc]
Found 1 error in 1 file (checked 1 source file)

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

使用链接的 mypy-play 示例或所示的 main.py 代码片段重现该诊断,然后跟踪拒绝泛型类成员的 ClassVar 和 Self 验证。比较协变和逆变的情况,并检查此规则现有的测试。当预期的逆变情况得到一致处理,同时无效的协变情况仍会被诊断时,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
devtools
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。