Python Up Your Code: Mixins

What are mixins and why would we need to use them?

Deck451
The Techlife

--

Photo by Maximalfocus on Unsplash

I guess we’ve all heard of mixins, at some point. But even if we didn’t, it’s still worth a look, albeit a brief one. It just might pay off in the end. This article aims at providing the reader with exactly that: a general, simple and precise overview of what mixins are and what can we gain out of using them.

So, what exactly is a mixin?

Simply put, a mixin is a class featuring a set of attributes / methods that can be used to provide extra functionality to another class. The mixin is not considered to be a base class itself. Typically, through inheritance, we ensure that objects get the functionality of the base class they’re extending. A mixin provides functionality without actually being included in the inheritance tree, functioning more as additions to the class, rather than proper ancestors. As such, the is-a relationship is no longer a thing when it comes to mixins, as we’re used to in a regular case of inheritance.

Now, you might then ask the very logical question: why don’t we simply add the mixin functionality to the base class, so the objects extending the base class can inherit all functionality from one place? And the answer’s pretty simple: because it wouldn’t make sense to do so. But let’s exemplify.

--

--

Deck451
The Techlife

Senior Software Engineer. Open-source contributor. Knowledge spreader. Fan of everything Python. Cybersecurity enthusiast. TryHackMe top 3%.