Mixin pattern does not play well with slots

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

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

Đánh giá

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

Hướng nghiên cứu

Bắt đầu với reproduction HasTimestampMixin và ConcreteMessage đã được cung cấp, sau đó chạy mypy và so sánh kết quả của nó với pyright và ty. Truy vết cách mypy kiểm tra các phép gán cho các thuộc tính có chú thích qua slots và MRO; công việc được hoàn tất khi ví dụ kiểm tra kiểu mà không có lỗi đã báo cáo, đồng thời giữ nguyên hành vi slot của lớp cụ thể.

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

Mô tả

feature pending

I am annotating a large codebase with heavy use of mixin patterns, where classes sharing similar attributes inherit the mixin for additional functionality.

One pattern in particular is failing on mypy (but passes on pyright and ty): where slots are involved in the concrete class. Let's look at this MRO, where HasTimestampMixin offers another way of setting the timestamp attribute.

from datetime import datetime


class HasTimestampMixin:
    __slots__ = []

    # Attribute contract: concrete subclasses provide this slot.
    timestamp: str | None

    @property
    def timestamp_dt(self) -> datetime | None:
        if self.timestamp is None:
            return None
        return datetime.fromisoformat(self.timestamp)

    @timestamp_dt.setter
    def timestamp_dt(self, dt: datetime | None) -> None:
        # this line fails with
        # Trying to assign name "timestamp" that is not in "__slots__" of type "repro.HasTimestampMixin"  [misc]
        self.timestamp = None if dt is None else dt.isoformat()


class ConcreteMessage(HasTimestampMixin):
    __slots__ = ["timestamp"]

    timestamp: str | None

    def __init__(self) -> None:
        self.timestamp = None


message = ConcreteMessage()
message.timestamp_dt = datetime(2026, 7, 30)
print(message.timestamp)  # Output: 2026-07-30T00:00:00

Removing the __slots__ in the mixin class fixes the typing issue but breaks the runtime by no longer having slots in the concrete class.

Ngôn ngữ chính
Python
Star
20.6k
Fork
3.3k
Merge trung bình
1 ngày 18 giờ
Pull request đã merge (30 ngày)
54

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.

Issue khác của python/mypy

Tất cả issue của python/mypy

Issue tương tự

Thêm issue về Python

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.