Simple Mixin usage in python


April 8, 2013

One situation where Mixins are useful in Python is when you need to modify  a method of similar classes that you are importing from a package.

For just a single class, it is easier to just create a derived class, but if the same modification must be applied to several classes, then it is cleaner to implement this modification once in a Mixin and then apply it to all of them.

Here an example in Django:

Django has several generic view classes that allow to pull objects from the database and feed them to the html templates.

One for example shows the detail of a specific object:

from django.views.generic.detail import DetailView

This class has a get_object method that gets an object from the database given a primary key.
We need to modify this method to allow access to an object only to the user that owns them.

We first implement a Mixin, i.e. an independent class that only implements the method we wish to override:

class OwnedObjectMixin(object):
def get_object(self, *args, **kwargs):
obj = super(OwnedObjectMixin, self).get_object(*args, **kwargs)
if not obj.user == self.request.user:
raise Http404
return obj

Then we create a new derived class which inherits both from the Mixin and from the class we want to modify.

class ProtectedDetailView(OwnedObjectMixin, DetailView):

This overrides the get_object method of DetailView with the get_object method of OwnedObjectMixin, and the call to super calls the get_object method of DetailView, so has the same effect of subclassing DetailView and override the get_object method, but we can be apply the same Mixin to other classes.