10.6 Handling multiple types with singledispatch
We’ll often have functions which have similar semantics but distinct implementations based on the type of data presented. We might have a function that works for either a subclass of NamedTuple
, or TypedDict
. The syntax for working with these objects is distinct, and we can’t use a single, generic Python function.
We have the following choices for working with data of distinct types:
Use the
match
statement with acase
clause for each distinct type.Use the
@singledispatch
decorator to define a number of closely-related functions. This will create the necessary type-matchingmatch
statement for us.
A small example arises when working with US postal data and spreadsheets. It’s common for a US postal ZIP code to be misinterpreted as an integer (or float) value. The town of Andover, MA, for example, has a postal code of 01810. A spreadsheet might misinterpret this as an integer, 1810, dropping the leading zero.
When...