python / python/mypy

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

オープン
#20,331 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

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. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

リンクされた mypy-play の例または示されている main.py のスニペットを使って診断を再現し、その後、ジェネリックなクラスメンバーを拒否している ClassVar と Self の検証を追跡します。共変の場合と反変の場合を比較し、このルールに対する既存のテストを確認します。意図された反変の場合が一貫して処理され、無効な共変の場合については引き続き診断されれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
devtools
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
45/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。