Hacktoberfest 2026:维护者为十月标记出来的 issue,仍然开放、适合新手。 浏览 Hacktoberfest issue

Mixin pattern does not play well with slots

未关闭
#21,794 14 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

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

调研方向

从提供的 HasTimestampMixin 和 ConcreteMessage 复现开始,然后运行 mypy,并将其结果与 pyright 和 ty 进行比较。追踪 mypy 如何跨越 slots 和 MRO 检查对带注解属性的赋值;完成的标准是示例在保留具体类的 slot 行为的同时通过类型检查,且不再出现所报告的错误。

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

描述

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.

主要语言
Python
星标
20.6k
派生
3.3k
平均合并
1 天 12 小时
30 天内合并 PR
58

贡献指南

打开贡献指南

从这里开始

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

python/mypy 的其他 Issue

查看 python/mypy 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

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