Function overloading with singledispatchmethod from functools


Python tip (>=3.8):

You can use singledispatchmethod to implement different (re)actions based on the first (non-self, non-cls) function's argument type.

For each type, you register an overloaded implementation.

For example, you can handle different events 👇

from functools import singledispatchmethod


class Event:
    pass


class UserSignedUp(Event):
    def __init__(self, email):
        self.email = email


class CustomerCanceledSubscription(Event):
    def __init__(self, email):
        self.email = email


class EventHandler:
    @singledispatchmethod
    def handle_event(event: Event):
        pass  # do nothing

    @handle_event.register
    def _(self, event: UserSignedUp):
        print(f"I will prepare resources for newly signed up user: {event.email}")

    @handle_event.register
    def _(self, event: CustomerCanceledSubscription):
        print(f"I will disable resources for customer:  {event.email}")


events = [
    UserSignedUp(email="[email protected]"),
    CustomerCanceledSubscription(email="[email protected]"),
]

handler = EventHandler()
for event in events:
    handler.handle_event(event)

# I will prepare resources for newly signed up user: [email protected]
# I will disable resources for customer:  [email protected]