Method overloading in Python
Even today, I still remember clearly how amazed I was at the concept of polymorphism while learning Object-Oriented Programming (OOP). I don’t know but it always made me think about the different stages of transformation of Goku in Dragon Ball Z or Ichigo in Bleach (same person, but multiples forms)…, but I digress here.
Polymorphism is one of the pillars of OOP, which consist on the ability of a programing language to provide a single interface to entities of different types or the use of a single symbol to represent multiples different type.
Here we are going to focus on static polymorphism. Static polymorphism or method overloading consists of the ability to have multiples methods with the same name but a different set of parameters, within the same class.
But let’s get back to python; Python native does not support method overloading (yeah I know), which can sometimes lead to bad smelling code like below:
One of the hidden gems of Python is the singledispatch decorator, which was introduced with Python 3.4 back in 2014.
Singledispatch is a part of the functools module, which will allow you to introduce some function overloading, and will allow your code to be readable and maintainable.
Here is exactly the same example but leveraging the singledispatcher:
As you can see this code is way easier to read, and making process_data handle a new type will be an easier and simple task while respecting the “Open-closed” principle.
For more details feel free to check the functools documentation page here.
To finish if you have been paying attention, you would have noticed that we used another pretty neat feature of python: the Dataclass.
We will be covering this marvelous Python feature in an upcoming article with wait for it … some great analogies.
Meanwhile happy coding ….