If you really want types, use classes. It removes the need for single dispatch, creates a self documenting namespace and saves you an import when you want to do the calculation.
import math
from dataclasses import dataclass
@dataclass
class Rectangle:
length: int
breadth: int
def area(self) -> int:
return self.length * self.breadth
@dataclass
class Circle:
radius: int
def area(self) -> float:
return math.pi * self.radius ** 2
@dataclass is of course not mandatory, and just make the code shorter.We are talking about very simple things here. No need to add complexity to them.
You could define it as a typing.Protocol too.
My point was just that, even if for some reason you prefer function overloading, the restrictions needed to fit within the constraints of functool.singledispatch arguably lead to cleaner code than the complicated mess in the OP article.
This would look messy if you implemented as just a single function with variable no of kwargs that you sniffed in the body, and I don't think applying function overloading alone as OP has done solves the underlying problem.
Indeed. Less is more sometimes.
And you could achieve the same thing with built-in functools.singledispatch by designing your API better
e.g. the example given is:
What if you need to calculate the area of another shape that uses a single integer value as the parameter?With singledispatch and some types: