Advertisement
Intermediate Python, Multiple Inheritance & MRO

What's the difference between mixing in an abstract base class (using abc.ABC) versus a plain mixin class?

Short answer

An ABC-based mixin can declare abstract methods that concrete combining classes must implement, enforced at instantiation time by ABCMeta -- providing a contract, not just shared implementation.

Save Python mock interview
Advertisement
AModel answer
An ABC-based mixin can declare abstract methods that concrete combining classes must implement, enforced at instantiation time by ABCMeta -- providing a contract, not just shared implementation. A plain mixin class only provides concrete, ready-to-use methods with no enforcement mechanism; combining classes can simply ignore or fail to satisfy any implicit expectations without an error until something actually breaks at runtime.
from abc import ABC, abstractmethod

class Comparable(ABC):
    @abstractmethod
    def compare_key(self): ...
    def __lt__(self, other):
        return self.compare_key() < other.compare_key()

class Product(Comparable):
    def __init__(self, price):
        self.price = price
    def compare_key(self):
        return self.price  # required, enforced by ABC
Real-world example
A sorting mixin defined as an ABC forces every combining class to implement compare_key(), catching the mistake at instantiation time instead of a confusing runtime error deep inside a sort operation.
Likely follow-ups
  • Why combine ABC enforcement with mixin convenience methods like this?
  • How does this differ from a Protocol-based structural approach?
Related topics