There are a few issues with the code you showed. I tried to go through those that I thought were most pressing in no particular order.
Avoid nested ABCs if possible
Since AbstractSerializer will be the abstract base class for your custom serializers, I would suggest defining the abstract methods like get_da_name on that class directly instead of having them in another, separate ABC like ThingsToImplement.
It makes the intent clearer because users of that AbstractSerializer will look at it and immediately see the work they will have to do.
The attributes that need to be present on every serializer subclass like constraints don't technically need to be declared on the ABC, but I think it makes sense for the same reason.
The purpose of Protocols
I would argue that the one of the main purposes of Protocol is to simplify doing exactly the things you are doing here. You define common behavior in a protocol that static type checkers can assume is available on a variable annotated with that Protocol.
In your specific case, it is up to you how finely grained your Protocol subclasses should be. If you want to be very pedantic, any Mix-in can have its own corresponding Protocol, but I would argue that is overkill most of the time. It really depends on how complex that "common behavior" becomes, which the Protocol is supposed to encapsulate.
In your example code I would only define one Protocol. (see below)
In addition, Protocol can be used in a generic way, which IMHO fits perfectly into the model serializer context since every serializer will have his instance set as can be seen in the type stubs for ModelSerializer (inheriting from BaseSerializer), which is also generic over a Model-bound type variable.
Allow ABCs to inherit from ConstraintsMixin
Since you set up your __init_subclass__ class method on ConstraintsMixin so strictly, you need to ensure that the actual ABC you want to create (i.e. AbstractSerializer) can inherit from it without triggering the error.
For this you simply add the ABCMeta check to __init_subclass__ first and avoid triggering the error on ABCs.
Use MySerializerProtocol in Mix-ins
Since your Mix-ins assume certain behavior in their instance methods, that is exactly where you can use MySerializerProtocol to annotate the self parameter.
Again, you may consider splitting the Protocol up further, if it gets too complex.
Solve the Metaclass conflict
Luckily, this is very easy in this case, since there are only two non-type Metaclasses involved here, namely the SerializerMetaclass from Django REST Framework and the ABCMeta from abc, and they don't actually conflict as far as I can see. You just need to define your own Metaclass that inherits from both and specify it in your serializer ABC.
Specify Django Model in subclasses
If you go the generic route (which seems more consistent to me), you should specify the concrete Django Model handled by the serializer, when you subclass AbstractSerializer.
If you don't want to go that route, mypy will complain in --strict mode upon subclassing ModelSerializer (that it is missing a type argument), but you can silence that. Also, you can omit the [M] everywhere in the code (see below) and instead just declare instance: Model on MySerializerProtocol.
Fully annotated example code
from abc import ABC, ABCMeta, abstractmethod
from dataclasses import dataclass
from typing import Any, Protocol, TypeVar
from django.db.models import Model
from rest_framework.serializers import ModelSerializer, SerializerMetaclass
M = TypeVar("M", bound=Model)
# Placeholder for a model to be imported from another module:
class ConcreteDjangoModel(Model):
pass
@dataclass
class Constraints:
width: int
height: int
class MySerializerProtocol(Protocol[M]):
"""For type annotations only; generic over `M` like `ModelSerializer`"""
my_number: int
constraints: Constraints
# From ModelSerializer:
instance: M
# From AbstractSerializer:
def get_da_name(self, s: str) -> str: ...
# From FooMixin:
def get_foo(self) -> str: ...
# From AnotherMixin:
def get_number(self) -> int: ...
# From ModelSerializer:
def to_representation(self, instance: M) -> Any: ...
class ConstraintsMixin:
# Class attributes that must be set by subclasses:
constraints: Constraints
def __init_subclass__(cls, **kwargs: Any) -> None:
if not isinstance(cls, ABCMeta) and not hasattr(cls, "constraints"):
raise NotImplementedError("Please add a constraints attribute")
super().__init_subclass__(**kwargs)
@classmethod
def print_constraints(cls: type[MySerializerProtocol[M]]) -> None:
print(cls.constraints.width, cls.constraints.height)
class FooMixin:
def get_foo(self: MySerializerProtocol[M]) -> str:
s = "something"
return self.get_da_name(s) if self.constraints.width > 123 else "Too small to be named"
def get_bar(self: MySerializerProtocol[M]) -> Any:
return self.to_representation(self.instance)
def from_another(self: MySerializerProtocol[M]) -> str:
return f"from {self.get_number()}"
class AnotherMixin:
def get_number(self: MySerializerProtocol[M]) -> int:
return self.my_number
def from_foo(self: MySerializerProtocol[M]) -> str:
return f"from {self.get_foo()}"
class AbstractSerializerMeta(SerializerMetaclass, ABCMeta):
"""To avoid metaclass conflicts in `AbstractSerializer`"""
pass
class AbstractSerializer(
ABC,
ConstraintsMixin,
FooMixin,
AnotherMixin,
ModelSerializer[M],
metaclass=AbstractSerializerMeta,
):
# Class attributes that must be set by subclasses:
constraints: Constraints
@abstractmethod
def get_da_name(self, s: str) -> str: ...
class MySerializer(AbstractSerializer[ConcreteDjangoModel]):
my_number: int = 7
constraints: Constraints = Constraints(1, 2)
def get_da_name(self, s: str) -> str:
self.my_number += 1
return f"hi {s}"
If you have an older Python version (below 3.9 I think), you may need to replace type[MySerializerProtocol[M]] with typing.Type[MySerializerProtocol[M]] in the print_constraints method.
Thanks for the fun little exercise. Hope this helps.
Feel free to comment, if something is unclear. I will try to amend my answer if necessary.