Skip to the solution
MediumDSA10 min read

What are mixins in Python?

1.2k views

The problem

Question presented to candidate: "You see classes like class UserView(LoginRequiredMixin, JsonMixin, View). What is a mixin, how does Python decide which method runs when several mixins define the same one, and what makes a mixin well designed?"

What a strong answer should cover:

  • A mixin is a small class that provides one capability (methods, rarely state) to be combined with other classes through multiple inheritance; it is not meant to be instantiated alone
  • Order matters: mixins go to the left of the main base class, because the MRO (C3 linearisation) searches left to right; on the wrong side the base method wins
  • Overriding mixins must call super(), which means the next class in the MRO, not the parent, so several mixins chain cooperatively
  • A mixin relies on a contract with its host (attributes or methods it expects); state-carrying mixins accept **kwargs and pass the rest on; empty __slots__ = () keeps them compatible with slotted classes
  • Real examples: collections.abc mixin methods, socketserver.ThreadingMixIn, Django class-based view mixins; alternatives are composition, class decorators and Protocols

Clarifying questions expected:

  • Does the capability need its own state, or only methods that use the host attributes?

Code / implementation expected: Yes β€” two small mixins combined on one class, with the MRO printed, ideally one that overrides a method with super().

  • oop
  • mixins

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonWriting mixins: placement, the MRO, cooperative super() and **kwargs
PythonMixins in the standard library and an ordering mixin

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 37 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How do uv workspaces and named dependency groups work?

Continue