Python clean code tip - use singledispatch instead of isinstance


Python clean code tip:

Use singledispatch instead of isinstance.

👇

from dataclasses import dataclass
from functools import singledispatch


@dataclass
class UserCanceledSubscription:
    username: str


@dataclass
class UserSubscribed:
    username: str


# with if
def process(event):
    if isinstance(event, UserSubscribed):
        print(f"Enable access to user {event.username}")
    elif isinstance(event, UserCanceledSubscription):
        print(f"Disable access to user {event.username}")


# with singledispatch
@singledispatch
def process(event):
    pass


@process.register(UserCanceledSubscription)
def _(event):
    print(f"Disable access to user {event.username}")


@process.register(UserSubscribed)
def _(event):
    print(f"Enable access to user {event.username}")


events = [
    UserSubscribed(username="johndoe"),
    UserCanceledSubscription(username="johndoe"),
]

for event in events:
    process(event)