Sub topic 11
Adding behavior with mixins
This chapter assumes you know how super() works, how Python builds the method resolution order (MRO), and how multiple inheritance behaves in a diamond. It builds on all three.
What a mixin is
A mixin is a small class that supplies one focused behavior to any class that lists it as a base. It is not meant to be instantiated alone, and it does not describe what an object is. A Point is not a kind of JsonMixin. The mixin only adds a capability, here JSON output.
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
print(Point(1, 2).to_json()) # {"x": 1, "y": 2}JsonMixin has no __init__ and keeps no state of its own. It relies on the host class having a __dict__. Any class that inherits it gets to_json() without copying code.
Conventions that keep mixins safe
- Give each mixin one job and name it for that job, usually with a
Mixinsuffix. - Keep the mixin free of its own
__init__state when you can. This avoids constructor-chaining problems in multiple inheritance. - Document what the mixin expects from the host class, such as attributes or methods it calls.
- Do not make mixins depend on each other.
Mixins that wrap a parent method
Some mixins change behavior around a method that the main base class defines. These must call super() so that the next class in the MRO still runs.
class LoggingMixin:
def save(self):
print(f"Saving {type(self).__name__}")
return super().save()
class Record:
def save(self):
return "saved"
class UserRecord(LoggingMixin, Record):
pass
print(UserRecord().save())
print([k.__name__ for k in UserRecord.__mro__])The output is:
Saving UserRecord
saved
['UserRecord', 'LoggingMixin', 'Record', 'object']Inside LoggingMixin.save(), super() does not mean "the parent of LoggingMixin". That parent is object, which has no save. It means "the next class after LoggingMixin in the MRO of type(self)". For a UserRecord instance, that next class is Record.
Base class order matters
Python searches bases from left to right. Put mixins before the main base class. If you reverse the order, Record.save() is found first. It never calls super(), so the mixin is silently skipped.
class LoggingMixin:
def save(self):
print(f"Saving {type(self).__name__}")
return super().save()
class Record:
def save(self):
return "saved"
class Wrong(Record, LoggingMixin):
pass
print(Wrong().save()) # saved (no log line)No error is raised. The only sign is that the expected behavior is missing.
Mixins versus other designs
| Approach | Use when | Cost |
|---|---|---|
| Mixin | Several unrelated classes need the same small behavior | The behavior depends on MRO order and on the host's attributes |
| Single inheritance | The subclass really is a specialized parent | Cannot share behavior across separate hierarchies |
| Composition | The behavior has its own state or needs swapping at runtime | Needs explicit delegation code |
If a mixin starts needing its own state or several collaborating methods, that is a sign to switch to composition, which the last chapter covers.
Exercise
In class Wrong(Record, LoggingMixin), why does Wrong().save() print no log line, and how do you fix it?
Show answer
The MRO is Wrong, Record, LoggingMixin, object. Python finds Record.save() first, and that method returns without calling super(), so LoggingMixin.save() never runs. Fix it by listing the mixin first: class Wrong(LoggingMixin, Record).
Exercise
Why can JsonMixin.to_json() fail on a host class that defines __slots__ and has no __dict__?
Show answer
The mixin reads self.__dict__. Instances of a class that uses __slots__ without a __dict__ slot have no such attribute, so the call raises AttributeError. The mixin has an unstated requirement on its host, which is why mixins should document what they expect.