python / python/mypy

Mixin pattern does not play well with slots

Open
#21,794 14 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature pending
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the provided HasTimestampMixin and ConcreteMessage reproduction, then run mypy and compare its result with pyright and ty. Trace how mypy checks assignments to annotated attributes across slots and the MRO; done means the example type-checks without the reported error while preserving the concrete class's slot behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.