Sub topic 11
Adding behavior with mixins
This chapter assumes you can write a subclass, override a method, call super(), and read a method resolution order (MRO) from __mro__. It builds on those to show how a mixin adds one narrow behavior to many unrelated classes.
What a mixin is
A mixin is a class that supplies one focused behavior and is meant to be listed as a base class next to other bases. It is not meant to stand alone as a "kind of thing". Dog is an Animal. A JsonMixin is not a kind of object. It is a bundle of methods you attach to a class.
Python has no mixin keyword. A mixin is an ordinary class used by convention. Three habits mark one:
- It has a narrow purpose, such as serializing, logging, or comparing.
- It is not instantiated directly.
- It usually has a name ending in
Mixin, so readers know how to treat it.
The standard library uses the pattern. socketserver.ThreadingMixIn turns a server into one that handles each request in its own thread. You combine it with a concrete server, as in class ThreadingTCPServer(ThreadingMixIn, TCPServer). The abstract classes in collections.abc also provide "mixin methods". If you implement __getitem__, __iter__, and __len__ on a Mapping subclass, you get get(), items(), keys(), and values() for free.
A first mixin
This mixin adds to_json() to any class whose state lives in __dict__.
import json
class JsonMixin:
def to_json(self):
return json.dumps(self.__dict__)
class Point(JsonMixin):
def __init__(self, x, y):
self.x = x
self.y = y
class User(JsonMixin):
def __init__(self, name, active):
self.name = name
self.active = active
print(Point(1, 2).to_json()) # {"x": 1, "y": 2}
print(User("Ana", True).to_json()) # {"name": "Ana", "active": true}Point and User share no parent other than object. The mixin gives both the same method without forcing them into one hierarchy. That is the main reason to use one: reusing behavior across classes that are not related by "is a".
Where the mixin goes in the base list
When a class has several bases, Python searches them in the MRO order, which follows the order you write them. The first class that defines a name wins. Because a mixin often wraps or overrides behavior in the concrete class, it normally goes before the concrete base.
Here is the mistake in action. Account has a deposit() method, and LoggedMixin is meant to wrap it.
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
class LoggedMixin:
def deposit(self, amount):
print(f"deposit({amount}) called")
return super().deposit(amount)
class WrongOrder(Account, LoggedMixin):
pass
class RightOrder(LoggedMixin, Account):
pass
WrongOrder("Ana").deposit(10) # prints nothing
RightOrder("Ana").deposit(10) # prints: deposit(10) called
print([k.__name__ for k in WrongOrder.__mro__])
# ['WrongOrder', 'Account', 'LoggedMixin', 'object']
print([k.__name__ for k in RightOrder.__mro__])
# ['RightOrder', 'LoggedMixin', 'Account', 'object']In WrongOrder, the lookup finds Account.deposit first, and the mixin's version is never reached. No error is raised, so the logging silently disappears. Always check __mro__ when a mixin seems to have no effect.
Cooperative mixins with super()
The LoggedMixin above does not know which class follows it in the MRO. It calls super().deposit(amount) and trusts that something later provides deposit. This is cooperative super(): each class does its part and passes the call along the MRO.
That makes mixins stackable. Here a second mixin validates the amount.
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
class LoggedMixin:
def deposit(self, amount):
print(f"deposit({amount}) called")
return super().deposit(amount)
class PositiveOnlyMixin:
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
return super().deposit(amount)
class SafeAccount(LoggedMixin, PositiveOnlyMixin, Account):
pass
acct = SafeAccount("Ana")
print(acct.deposit(50))
try:
acct.deposit(-5)
except ValueError as exc:
print("Rejected:", exc)
print([k.__name__ for k in SafeAccount.__mro__])The output is:
deposit(50) called
50
deposit(-5) called
Rejected: amount must be positive
['SafeAccount', 'LoggedMixin', 'PositiveOnlyMixin', 'Account', 'object']The call travels SafeAccount, then LoggedMixin, then PositiveOnlyMixin, then Account. Logging happens before validation, so the rejected deposit is still logged. If you swap the two mixins, validation runs first and a rejected call is never logged. The base list order is therefore part of the behavior, not a style choice.
Mixins that need state
Mixin methods often need data. There are three common ways to supply it, from safest to riskiest:
- Use class attributes with defaults, which the host class can override.
- Read attributes the host class is documented to provide, such as
self.name. - Define
__init__in the mixin and cooperate with the rest of the chain.
The third option needs care. A mixin does not know which class comes after it, so it cannot call super().__init__(name) with specific arguments. The usual pattern is to take what it needs by keyword and forward everything else.
class TagMixin:
def __init__(self, *args, tags=(), **kwargs):
super().__init__(*args, **kwargs)
self.tags = list(tags)
class Item:
def __init__(self, name):
self.name = name
class TaggedItem(TagMixin, Item):
pass
lamp = TaggedItem("lamp", tags=["home", "lighting"])
print(lamp.name, lamp.tags) # lamp ['home', 'lighting']TagMixin.__init__ receives "lamp" in args and the tags by keyword. It forwards "lamp" to Item.__init__ and then stores tags. If the mixin forgot to call super().__init__(*args, **kwargs), Item.__init__ would never run and name would be missing. This is the same mistake as forgetting super().__init__() in a plain subclass, but harder to spot because the missing call sits in a class you did not write.
Documenting what a mixin expects
A mixin often relies on the host class. JsonMixin assumes the instance has a __dict__ whose values json can encode. That assumption fails in two ways:
- A class that defines
__slots__has no__dict__, soself.__dict__raisesAttributeError. - An instance holding a
set, adatetime, or another objectjsoncannot encode raisesTypeError.
import json
class JsonMixin:
def to_json(self):
return json.dumps(self.__dict__)
class Slotted(JsonMixin):
__slots__ = ("x",)
def __init__(self, x):
self.x = x
class Tagged(JsonMixin):
def __init__(self):
self.tags = {"a", "b"}
for obj in (Slotted(1), Tagged()):
try:
print(obj.to_json())
except (AttributeError, TypeError) as exc:
print(type(exc).__name__, "-", exc)Both calls fail, with different error types. State requirements in the mixin's docstring, or have the mixin call a hook that the host class implements, such as self.to_dict(). A hook turns an implicit assumption into a visible contract, and the mixin no longer depends on __dict__.
Mixins compared with the alternatives
| Approach | Best when | Main cost |
|---|---|---|
| Mixin | The same small behavior is needed by many unrelated classes | Order sensitivity and hidden assumptions about the host |
| Single inheritance | The subclass really is a specialized version of the parent | Tight coupling to one parent |
| Abstract base class | You need to force subclasses to implement a method | It states a requirement but supplies little behavior |
| Composition | The behavior has its own state or may change at runtime | You write explicit delegation calls |
Mixins and abstract base classes combine well. A mixin can implement concrete helpers on top of an abstract method, as collections.abc.Mapping does: subclasses supply __getitem__, __iter__, and __len__, and the base supplies get() and items().
Common problems
- The mixin has no effect. Check
__mro__. A concrete class listed before the mixin may define the method first. - A mixin overrides a method but never calls
super(). It cuts the chain, so later classes (including the concrete base) never run. Callsuper()unless you intend to replace the behavior. - Two mixins define the same method name. The earlier one in the MRO wins, and the other is skipped unless the winner calls
super(). Use distinct names or make both cooperative. - Mixins that depend on each other. If
AneedsBto be present, the pair is really a single design. Merge them, or use composition. - Too many bases. A class with five mixins is hard to reason about, because the call path is the MRO and you must read it to know the behavior. When you cannot predict the order of calls at a glance, replace some mixins with composed objects.
Exercise
Given the classes below, what does Report().render() return, and what is the MRO of Report?
class Base:
def render(self):
return ["base"]
class UpperMixin:
def render(self):
return [s.upper() for s in super().render()]
class FrameMixin:
def render(self):
return ["["] + super().render() + ["]"]
class Report(UpperMixin, FrameMixin, Base):
pass
Show answer
The MRO is Report, UpperMixin, FrameMixin, Base, object. The call starts in UpperMixin.render, which calls super().render() and reaches FrameMixin.render. That calls Base.render, which returns ["base"]. FrameMixin wraps it as ["[", "base", "]"], and UpperMixin then upper-cases every item. The result is ["[", "BASE", "]"]. Note that UpperMixin transforms the result after the rest of the chain runs, so the brackets are upper-cased too (they are unchanged by upper()).
Exercise
A class Order(Model, AuditMixin) is supposed to log every call to save(). AuditMixin.save() prints a message and then calls super().save(). No message ever appears, and there is no error. What is wrong, and how do you fix it?
Show answer
Model is listed before AuditMixin, so the MRO finds Model.save() first and never reaches the mixin's version. Reorder the bases to class Order(AuditMixin, Model). Printing Order.__mro__ confirms the new order, with AuditMixin ahead of Model.