Python - function overloading with singledispatch
Python tip:
You can use
singledispatchto implement different (re)actions based on the first function's argument typeFor each type, you register an overloaded implementation
For example, you can handle different events like so:
from functools import singledispatch class Event: pass class UserSignedUp(Event): def __init__(self, email): self.email = email class CustomerCanceledSubscription(Event): def __init__(self, email): self.email = email @singledispatch def handle_event(event: Event): pass # do nothing @handle_event.register(UserSignedUp) def _(event: UserSignedUp): print(f"I will prepare resources for newly signed up user: {event.email}") @handle_event.register(CustomerCanceledSubscription) def _(event: CustomerCanceledSubscription): print(f"I will disable resources for customer: {event.email}") events = [ UserSignedUp(email="[email protected]"), CustomerCanceledSubscription(email="[email protected]"), ] for event in events: handle_event(event) # I will prepare resources for newly signed up user: [email protected] # I will disable resources for customer: [email protected]