Mixin pattern does not play well with slots
还没有人认领这个 Issue。
评估
调研方向
从提供的 HasTimestampMixin 和 ConcreteMessage 复现开始,然后运行 mypy,并将其结果与 pyright 和 ty 进行比较。追踪 mypy 如何跨越 slots 和 MRO 检查对带注解属性的赋值;完成的标准是示例在保留具体类的 slot 行为的同时通过类型检查,且不再出现所报告的错误。
由索引模型根据 Issue 内容生成。
描述
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
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
python/mypy 的其他 Issue
-
bug
难度 2/5 1-3 小时 新手友好度 78/100
-
bug
难度 2/5 1-3 小时 新手友好度 76/100
-
documentation
难度 2/5 1-3 小时 新手友好度 72/100
-
bug topic-configuration topic-error-reporting
难度 2/5 1-3 小时 新手友好度 68/100
-
bug topic-attrs
难度 2/5 1-3 小时 新手友好度 62/100
相似的 Issue
-
essnmx good first issue
难度 1/5 1 小时以内 新手友好度 95/100
-
难度 2/5 1-3 小时 新手友好度 65/100
syfoud/Simulated_Scepter#174 ·
-
难度 2/5 1-3 小时 新手友好度 75/100
Giskard-AI/giskard-oss#2840 · 1 条评论 ·
-
A claim comment carrying the issue number is silently declined while the workflow reports success 未关闭area: repo bug perceived difficulty: 2
难度 2/5 1-3 小时 新手友好度 70/100
-
难度 2/5 1-3 小时 新手友好度 75/100
yeti-platform/yeti#1380 ·