Python is one of the most popular programming languages in use today—and for good reasons: it's open source, it has a wide range of uses (such as web programming, business applications, games, scientific programming, and much more), and it has a vibrant and dedicated community supporting it. This community is the reason we have such a large, diverse range of software packages available in the Python Package Index (PyPI) to extend and improve Python and solve the inevitable glitches that crop up.
In this series, we'll look at seven PyPI libraries that can help you solve common Python problems. Today, we'll examine singledispatch, a library that allows you to add methods to Python libraries retroactively.
Imagine you have a "shapes" library with a Circle class, a Square class, etc.
A Circle has a radius, a Square has a side, and a Rectangle has height and width. Our library already exists; we do not want to change it.
However, we do want to add an area calculation to our library. If we didn't share this library with anyone else, we could just add an area method so we could call shape.area() and not worry about what the shape is.
While it is possible to reach into a class and add a method, this is a bad idea: nobody expects their class to grow new methods, and things might break in weird ways.
Instead, the singledispatch function in functools can come to our rescue.
raise NotImplementedError("cannot calculate area for unknown shape",
The "base" implementation for the get_area function fails. This makes sure that if we get a new shape, we will fail cleanly instead of returning a nonsense result.
return shape.side ** 2
return math.pi * (shape.radius ** 2)
One nice thing about doing things this way is that if someone writes a new shape that is intended to play well with our code, they can implement get_area themselves.
from area_calculator import get_area
return math.pi * shape.horizontal_axis * shape.vertical_axis
Calling get_area is straightforward.
This means we can change a function that has a long if isintance()/elif isinstance() chain to work this way, without changing the interface. The next time you are tempted to check if isinstance, try using singledispatch!
In the next article in this series, we'll look at tox, a tool for automating tests on Python code.