Search code examples
pythoninheritancemultiple-inheritance

DRY with super() in Python


Apologies if this is a dumb question but I couldn't find it by search. I have Python code to the effect of the following:

class CustomListView(ListView):
    def dispatch(self, request : HttpRequest, *args, **kwargs):
        # ... long blurb doing something with request and super, e.g.
        return super().dispatch(request, *args, **kwargs)
class CustomDetailView(DetailView):
    def dispatch(self, request : HttpRequest, *args, **kwargs):
        # ... long blurb doing something with request and super, e.g.
        return super().dispatch(request, *args, **kwargs)

(This is in context of Django, but I don't think it should matter.)

These two dispatch functions are exactly the same, so I feel like this is a blatant violation of DRY principles. But the problem is because the super() is used, I can't figure out how I would write this function only once and have the inheritance work out, assuming super is called a lot of times.

What's the best way to deal with this?


Solution

  • Just to mark this as solved, the relevant keyword I was looking for is mixins. There's a couple links in the comments, one to a past SO answer and one to Django mixins specifically. Thanks all.