Whereas with Protocols it's gonna be ( good tutorial ): I think that is not a good example of how to write programs. What he did by having protocols I would have done by using mixins. The way that I see objects is that they have various capabilities that can be mixed in. multiple inheritance in python would have been a much better way to implement that example in my opinion. I would also say that the author of this tutorial needs to learn a thing or 2 about an inversion of control and dependency injection. The author basically sets up a straw man problem and then solves his straw man problem. He had no business creating instances of the object outside of the class itself. If he had simply called a constructor methods within the classes then the other class wouldn't have been attempting to make instances of those other classes. Answer from thedeepself on reddit.com
🌐
Sinavski
sinavski.com › home › interfaces abc vs. protocols
Interfaces: abc vs. Protocols - Oleg Sinavski
August 1, 2021 - I would love Python to separate them on a language level, but it is unlikely to happen. Implicit protocols have an advantage here. They allow you to avoid messy inheritance altogether. Last but not least, you can count the number of lines of code you need to define an interface. With abc, you must have an abstractmethod decorator for every method.
🌐
Reddit
reddit.com › r/python › interfaces with protocols: why not ditch abc for good?
r/Python on Reddit: Interfaces with Protocols: why not ditch ABC for good?
January 22, 2023 -

Hello, if one finds interfaces useful in Python (>=3.8) and is convinced that static type-checking is a must, then why not ditch ABC and always use Protocols? I understand that the fundamental idea of a protocol is slightly different from an interface, but in practice, I had great success replacing abc's with Protocols without regrets.

With abc you would write (https://docs.python.org/3/library/abc.html) :

from abc import ABC, abstractmethod

class Animal(ABC):
   @abstractmethod
   def eat(self, food) -> float:
       pass

Whereas with Protocols it's gonna be (good tutorial):

from typing import Protocol

class Animal(Protocol):
   def eat(self, food) -> float:
       ...

Scores in my subjective scoring system :)

CapabilityABCProtocols
Runtime checking11 (with a decorator)
Static checking with mypy11
Explicit interface (class Dog(Animal):)11
Implicit interface with duck-typing (class Dog:)0.5 (kind of with register, but it doesn't work with mypy yet)1
Default method implementation (def f(self): return 5)-1 (implementations shouldn't be in the interfaces)-1 (same, and mypy doesn't catch this)
Callback interface01
Number of code lines-1 (requires ABC inheritance and abstracmethod for every method)0 (optionalProtocol inheritance)
Total score1.54

So I do not quite see why one should ever use ABC except for legacy reasons. Other (IMHO minor) points in favour of ABC I've seen were about interactions with code editors.

Did I miss anything?

I put more detailed arguments into a Medium. There are many tutorials on using Protocols, but not many on ABC vs Protocols comparisons. I found a battle of Protocols vs Zope, but we are not using Zope, so it's not so relevant.

🌐
Justin A. Ellis
jellis18.github.io › post › 2022-01-11-abc-vs-protocol
Abstract Base Classes and Protocols: What Are They? When To Use Them?? Lets Find Out! - Justin A. Ellis
January 11, 2022 - In Python there are two similar, yet different, concepts for defining something akin to an interface, or a contract describing what methods and attributes a class will contain. These are Abstract Base Classes (ABCs) and Protocols.
🌐
Python
docs.python.org › 3 › library › abc.html
abc — Abstract Base Classes
This module provides the infrastructure for defining abstract base classes (ABCs) in Python, as outlined in PEP 3119; see the PEP for why this was added to Python.
🌐
Medium
medium.com › @pouyahallaj › introduction-1616b3a4a637
Python Protocols vs. ABCs: A Comprehensive Comparison of Interface Design | Medium
May 29, 2023 - However, ABCs in Python have some shortcomings. One of the main limitations is that they rely on subclassing, meaning a class can only inherit from one ABC. This restriction can be problematic in cases where multiple inheritance is needed. This is where Protocols come into play.
🌐
Python
typing.python.org › en › latest › spec › protocol.html
Protocols — typing documentation
See Python data model for details.) The attributes (variables and methods) of a protocol that are mandatory for another class for it to be assignable to the protocol are called “protocol members”. Protocols are defined by including a special form typing.Protocol (an instance of abc.ABCMeta) in the base classes list, typically at the end of the list.
🌐
Medium
medium.com › @kandemirozenc › understanding-interfaces-abc-protocol-and-duck-typing-in-python-866ca32ab2a0
Understanding Interfaces, ABC, Protocol and Duck Typing in Python | by kandemirozenc | Medium
December 7, 2024 - In Python, there is no direct equivalent of Java’s “interface,” but similar functionality can be achieved using the abc module (Abstract Base Classes). Since Python embraces duck typing, enforcing a specific interface is not mandatory.
Find elsewhere
🌐
GitConnected
levelup.gitconnected.com › python-interfaces-choose-protocols-over-abc-3982e112342e
Python interfaces: abandon ABC and switch to Protocols | by Oleg Sinavski | Level Up Coding
January 19, 2023 - A protocol is a formalization of Python’s “duck-typing” ideology. There are many great articles on structural typing in Python (for example, see this tutorial). Protocols and interfaces are different beasts in theory, but a protocol does the job. I had great success replacing abc with Protocols without any downsides.
🌐
Python
docs.python.org › 3 › library › collections.abc.html
collections.abc — Abstract Base Classes for Containers
ABC for generator classes that implement the protocol defined in PEP 342 that extends iterators with the send(), throw() and close() methods.
🌐
YouTube
youtube.com › arjancodes
Protocols vs ABCs in Python - When to Use Which One? - YouTube
💡 Learn how to design great software in 7 steps: https://arjan.codes/designguide.In this video, I’m revisiting Protocols and ABCs in Python, essential for c...
Published   July 5, 2020
Views   41K
🌐
GitHub
gist.github.com › Integralist › cc04c2c34a988be26e56fe2f3ea95aff
[Python Interfaces via Protocols and Abstract Base Classes (with Metaclasses)] #python #interfaces #protocols #design #collections #abc #iterator #sized #metaclasses #abstract · GitHub
But if we implement the __len__ magic method, we are now telling Python that we support the Sized protocol: class Team: def __init__(self, members): self.members = members def __len__(self): return len(self.members) t = Team(['foo', 'bar', 'baz']) t.members # ['foo', 'bar', 'baz'] len(t) # 3 · There are many different protocols, such as: collections.abc.Iterator which if we were to implement the __iter__ and __next__ magic methods, then we'd be able to use a for loop construct on our object:
🌐
how.wtf
how.wtf › abc-vs-protocol-in-python.html
ABC vs Protocol in Python | how.wtf
December 16, 2023 - Before typing was released for Python, the ABC class reigned as champion for describing shape and behaviors of classes. After type annotations, ABC and @abstractmethod were still used to describe the behaviors: they felt ‘interface-like’. Then, Protocol was released and introduced a new way for declaring class behaviors.
🌐
Hacker News
news.ycombinator.com › item
Where would you use `typing.Protocol` where you wouldn't use an abstract base cl... | Hacker News
March 19, 2021 - The only time I've ever used `Protocol` is to define a type that makes it explicit that I need an object to have a `__str__` implementation: · Abstract base classes require everything to extend from a base-level object, and also inherit it's default implementations.
🌐
Medium
tconsta.medium.com › python-interfaces-abc-protocol-or-both-3c5871ea6642
Modern Python Interfaces: ABC, Protocol, or Both? | by Konstantin T | Medium
November 14, 2025 - ABCs belong to the “nominal” world — you declare you are something by inheriting from a base class. Python enforces abstract methods at runtime; try to instantiate an incomplete subclass and you get an error.
🌐
DEV Community
dev.to › meseta › factories-abstract-base-classes-and-python-s-new-protocols-structural-subtyping-20bm
Python's new Protocols (Structural subtyping), Abstract Base Classes, and Factories - DEV Community
August 18, 2020 - Python has a built-in library for this called abc which stands for Abstract Base Class. The idea is to define an abstract base class for the file handler, against which new concrete implementations of different file handlers can be built.
🌐
Romerogabriel
romerogabriel.github.io › mastering-python › classes_objects › interfaces_protocols_abc
Interfaces, Protocols, and ABCs - Mastering Python
Static protocols can be verified by static type checkers, which is not possible for dynamic protocols. Python offers another explicit means of defining an interface in code: the abstract base class (ABC).
Top answer
1 of 1
4

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.

🌐
Reddit
reddit.com › r/python › protocols vs abstract base classes in python
r/Python on Reddit: Protocols vs Abstract Base Classes in Python
December 1, 2024 -

Hi everyone. Last time I shared a post about Interface programming using abs in Python, and it got a lot of positive feedback—thank you!

Several people mentioned protocols, so I wrote a new article exploring that topic. In it, I compare protocols with abstract base classes and share my thoughts and experiences with both. You can check it out here: https://www.tk1s.com/python/protocols-vs-abstract-base-classes-in-python Hope you'll like it! Thanks!

🌐
Andrewbrookins
andrewbrookins.com › technology › building-implicit-interfaces-in-python-with-protocol-classes
Building Implicit Interfaces in Python with Protocol Classes – Andrew Brookins
July 5, 2020 - Any time you would use an interface in another language, you can now do the same thing with protocol classes in Python. Where previously you might have defined an ABC and subclassed it as a way to define (and type-check, with mypy) an interface, you can now use a protocol class.