4

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?

Evan Chen
  • 183
  • 8
  • 3
    Have you [tried mixins?](https://docs.djangoproject.com/en/3.2/topics/class-based-views/mixins/#more-than-just-html) – Abdul Niyas P M Jul 05 '21 at 04:03
  • 1
    This [other SO post](https://stackoverflow.com/q/533631/3545273) contains in depth discussion about mixins. – Serge Ballesta Jul 05 '21 at 07:01
  • 1
    It's not as trivial as it looks. The *compiler* determines what arguments to pass to `super` based on where it is called. You might have to take care with the order in which the base classes appear in order to ensure that the correct `dispatch` method is called. – chepner Jul 06 '21 at 17:21
  • 1
    Plus, if two classes in the same inheritance heirarchy want to use a `dispatch` method that looks like this, a mixin is not going to work. There are a lot of differences between putting this method in a mixin and putting it in `CustomListView` or `CustomDetailView` directly. I'd avoid using a mixin for this. – user2357112 Jul 06 '21 at 17:23

1 Answers1

2

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.

Evan Chen
  • 183
  • 8