python / python/mypy

Question: How to bound a mixin to a subclass

Open
#8,705 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

question topic-inheritance topic-protocols
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

I created a mixin for Django models and I would like to know how to properly type it, e.g.:

from django.db import models

T = TypeVar("T", bound=models.Model)


class SafeCreateMixin:
    @classmethod
    @transaction.atomic()
    def safe_create(cls: Type[T], **kwargs) -> Optional[T]:
        try:
            return cls.objects.create(**kwargs)
        except IntegrityError as e:
            return None

class MyModel(SafeCreateMixin, models.Model):
    ....

It fails with the following error:

error: The erased type of self "Type[django.db.models.base.Model]" is not a supertype of its class "Type[SafeCreateMixin]"

I understood that the mypy docs recommend creating a Protocol for mixins, but in my case, I just want to enforce that my mixins are added to a subclass of models.Model

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 by reproducing the reported error with the SafeCreateMixin and MyModel example, then read the mypy documentation on mixins and Protocols. Determine whether the requested subclass constraint is supported or needs a design decision; done means the behavior and recommended approach are clearly established.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.