A untold story about “composition” and “multiple inheritance” in PYTHON
Disclaimer: This article assumes you know idea of decorators in python.
Python has always been this awesome language where you have first class support for decorator. Decorator allows you to write modular, compositional and loosely coupled code. It is O of “SOLID Principle” i.e. open to extension and close to modification.
As always, I was bored writing decorators and so I tinkered around different ways I can apply compositional pattern in python without messing up with decorators. I knew python supported “multiple inheritance”, but python community hated the idea of multiple inheritance due to fear of Diamond problem. There are basically two strict rules that community have adopted for avoiding such issues. They are as follows:
- Avoid multiple inheritance.
- Avoid super() keyword if possible (UNPREDICTABLE)
I did the opposite. I extensively tried using multiple inheritance and super keyword in achieving compositional pattern. I tried for days and nothing seem to make sense. Every attempt ended up in deep and darkest rabbit hole.
After hurting my brain for months, I was able to address compositional pattern without using “decorator”, and my good god, results = MIND BLOWN🎉.
This article will be long winded, boring lecture on composition pattern using just super keyword and multiple inheritance. We clearly don’t want to go that route. I would like to share the code snippet of validation library that we built for validating parsed JSON object in python.
Check out the library itself for diving deep into how super keyword can be used in writing program that adheres to the principle of “Separation of Concern”.
WIP. Contribute to RobusGauli/jsonvalidate development by creating an account on GitHub.
- Use multiple inheritance only when you absolutely understand how base classes during multiple inheritance are linearized using Class Resolution Algorithm.
- Understand the “method resolution order” and know how you can manipulate linearization during class resolution before abandoning “decorator” for composition.
Once you understand how all these delicate parts are managed in python, you will realize super is super and we should absolutely give it a shot. It will hurt your good old brain for a while but the API you can build using this pattern is absolute magic. Cheers 🎉 🎉!!