Why does the convention of listing mixins before the primary base class matter for MRO and method overriding?
Short answer
Python's MRO respects the left-to-right order bases are listed as a tiebreaker (local precedence order), so `class Foo(Mixin, Base):` means Mixin's methods take precedence over Base's when both define the same method name, since Mixin appears first in the MRO.
Advertisement
AModel answer
Python's MRO respects the left-to-right order bases are listed as a tiebreaker (local precedence order), so `class Foo(Mixin, Base):` means Mixin's methods take precedence over Base's when both define the same method name, since Mixin appears first in the MRO. Reversing the order (`class Foo(Base, Mixin):`) would let Base's methods shadow the Mixin's, likely defeating the mixin's purpose of adding or overriding specific behavior.
class LoggingMixin:
def save(self):
print('Logging save')
super().save()
class Base:
def save(self):
print('Base save')
class Model(LoggingMixin, Base): # Mixin first: its save() runs, then chains to Base
pass
Model().save() # Logging save, then Base saveReal-world example
A code review catches a bug where `class View(TemplateMixin, LoginRequiredMixin, View)` accidentally puts the auth mixin after TemplateMixin, causing template rendering to happen before the login check runs.
Likely follow-ups
- What happens if you reverse the mixin and base order here?
- How would you verify the resulting order with __mro__?
Related topics