python / python/mypy

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

Đang mở
#20,331 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

bug
Ngôn ngữ chính
Python
Star
20.6k
Fork
3.3k
Chỉ số merge pull request
Chỉ số pull request đang chờ

Mô tả

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)

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Tái hiện chẩn đoán bằng ví dụ mypy-play được liên kết hoặc đoạn mã main.py được hiển thị, sau đó lần theo quá trình xác thực ClassVar và Self đang từ chối thành viên lớp generic. So sánh các trường hợp đồng biến và phản biến, đồng thời kiểm tra các test hiện có cho quy tắc này. Được xem là hoàn tất khi trường hợp phản biến dự kiến được xử lý nhất quán, trong khi trường hợp đồng biến không hợp lệ vẫn được chẩn đoán.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python
Lĩnh vực
devtools
Loại issue
Lỗi
Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
45/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.