79244386

Date: 2024-12-02 14:15:10
Score: 0.5
Natty:
Report link

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

decorators.py

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

usage.py

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)

results

A case_id=8
B
Reasons:
  • Blacklisted phrase (1): stackoverflow
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: MichaƂ Ligus