Discover more from Daily Dose of Data Science
One of the Most Critical Pillars of OOP is Missing from Python
But here's how to introduce it.
One thing I have always hated about Python OOP is that Python provides no native support for function overloading.
Function overloading is critical to polymorphism, wherein, we may have multiple functions with:
Same name, and
Different number (or type) of parameters.
But in Python, if we define two (or more) functions with the same name and different parameters, Python will only consider the latest definition corresponding to that function name.
This is depicted below.
As depicted above, the latest definition of
add() had three parameters. That is why passing two arguments raised an error.
This restricts us from writing good polymorphic code in Python.
Of course, there are ways to prevent this error, as depicted below:
Also, if the same parameter can take multiple data types, we can write (somewhat) polymorphic code by adding multiple check statements using
But this isn’t as elegant as defining multiple functions with different data types like we can do in, say, C++, is it?
C++ automatically invokes the correct method corresponding to the argument data type.
Lately, while exploring this for one of my projects, I found a pretty handy way to enable function overloading in Python and thought it’d be quite useful for many of you.
As depicted above, we have multiple functions with the same name and different parameters.
@dispatch decorator allows us to invoke the correct function corresponding to the parameters passed during the function call.
Another cool thing about the
@dispatch decorator is that it raises an error when the function call does not match any of the function definitions:
This allows us to identify errors which can often go unnoticed.
Isn’t that cool?
In a dummy experimentation, I did notice a slight increment in the run time. But the order of increase was in nanoseconds or so, which can be safely ignored.
👉 Over to you: What other cool Python libraries you are aware of?
Thanks for reading Daily Dose of Data Science! Subscribe for free to learn something new and insightful about Python and Data Science every day. Also, get a Free Data Science PDF (550+ pages) with 320+ tips.
👉 If you liked this post, don’t forget to leave a like ❤️. It helps more people discover this newsletter on Substack and tells me that you appreciate reading these daily insights.
The button is located towards the bottom of this email.
Thanks for reading!
Latest full articles
If you’re not a full subscriber, here’s what you missed last month:
To receive all full articles and support the Daily Dose of Data Science, consider subscribing:
👉 Tell the world what makes this newsletter special for you by leaving a review here :)
👉 If you love reading this newsletter, feel free to share it with friends!