I modified the example from https://stackoverflow.com/a/36837332/6794247 like below for my case i.e. by an instance of enum and with additional parameters if needed
from enum import Enum
from typing import Type
class enum_dispatch_method(object):
def __init__(self, method):
self.registry = {}
self.function = method
def __get__(self, instance, owner):
if instance is None:
return self
def _method(*args, **kwargs):
arguments = list(args)
enum = arguments.pop(0)
method = self.registry[enum]
return method.__get__(instance, owner)(*arguments, **kwargs)
return _method
def register(self, enum):
def method_register(method):
self.registry[enum] = method
return method
return method_register
class Test(Enum):
A = 1
B = 2
class Strategy:
@enum_dispatch_method
def handle(self, enum, case_id: int | None = None):
raise NotImplmsentedError
@handle.register(Test.A)
def for_a(self, case_id):
print(f"A {case_id=}")
@handle.register(Test.B)
def for_b(self):
print(f"B")
s = Strategy()
s.handle(Test.A, case_id=8)
s.handle(Test.B)
A case_id=8
B