Search code examples
pythondecoratormixinspython-decorators

Python: Use of decorators v/s mixins?


I have understood the basics of decorators and mixins. Decorators add a new functionality to an object without changing other object instances of the same class, while a mixin is a kind of multiple inheritance used to inherit from multiple parent classes.

Does it mean that decorators should be used when you'd need to modify only a single object instance and use mixins when you'd need a whole new class of objects. Or, is there something more to it that I might be missing? What can be real life use cases for both?


Solution

  • In my opinion, you need mixins when you have a few different classes that should have same functionality.

    Good examples of using mixins are Django's class-based views. For example, you have a few different classes: FormView, TemplateView, ListView. All of them have one similar piece of functionality: they have to render templates. Every one of these classes has a mixin, which adds methods required for template rendering.

    Another example is if you needed to add a class for an API that returns a JSON result. It could also be inherited from a base, View class. You simply skip template mixins, and define what you need (and probably write your own mixin for JSON encoding).

    Additionally, you may override some of methods proposed in mixins which allow you to modify some parts of common code for your local case. It's all about OOP, buddy!

    Long story short: mixins add new functionalities.

    Decorators are used to modify existing functionalities. For example, if you need to log what is returned from a method in your class. The right choice here is a decorator (added to appropriate methods).

    Hope it is helpful. If not, please ask questions. I will update my response.