Using the Single-Dispatch Method in the Real World
A Real-World Example of a Single-Dispatch Method. As a more realistic example of using
@singledispatchmethod, say you need to continue adding features to your
Person class. This time, you need to provide a way to compute the approximate age of a person based on their birth date. To add this feature to
Person, you can use a helper class that handles all the information related to the birth date and age.
Go ahead and create a file called
person.py in your working directory. Then add the code seen on-screen to it. Here you import
datetime so that you can later convert any input date to a
These lines define the class initializer as a single-dispatch generic method using
@singledispatchmethod. This is the method’s base implementation, and it raises a
ValueError for unsupported date formats.
Here you register implementation that processes dates that come as Unix time in seconds since the epoch. This time, you register two instances of the overloaded method by stacking the
.register decorator with the
Finally, these lines provide a regular method to compute the age of a given person. Note that the implementation of
age() isn’t totally accurate because it doesn’t consider the month and day of the year when calculating the age.
The overloaded initializer of the
BirthInfo class will initialize
._birth_info according to the user’s birth date. Then you define
age() as a property to provide a computed attribute that returns the person’s current approximate age.
The main limitation of the single-dispatch method technique is that it relies on a single argument, the first argument after
self. If you need to use multiple arguments for dispatching appropriate implementations, then check out some existing third-party libraries, such as
Become a Member to join the conversation.