Mixin pattern does not play well with slots
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit der bereitgestellten Reproduktion von HasTimestampMixin und ConcreteMessage, führe dann mypy aus und vergleiche dessen Ergebnis mit pyright und ty. Verfolge, wie mypy Zuweisungen zu annotierten Attributen über slots und die MRO hinweg prüft; fertig ist die Aufgabe, wenn das Beispiel ohne den gemeldeten Fehler typgeprüft wird und dabei das Slot-Verhalten der konkreten Klasse erhalten bleibt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Ruhig
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 48/100