Skip to content

Mixin pattern does not play well with slots #21794

Description

@alexprengere

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions