My favorite way to implement this is with decorators. I used this to make a dispatch table for reading objects from a MySQL database.
(Yes I know I should be using UserDict below. You should too and don’t subclass dict like I did.)
classFuncRegistry(dict):
"""Creates a registry of hashable objects to function mappings."""def__init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
defregister_for(self, key: Hashable) -> Callable:
"""Decorator to register functions in the registry.
Parameters
key: Hashable
The key which should point to this function
Returns: Callable
Returns a decorator that registers the function to the key"""defdecorator(fn: Callable) -> Callable:
self[key] = fn
return fn
return decorator
qreg = FuncRegistry()
@qreg.register_for('foobr')defhandle_foobr(arg1, arg2):
# do something here thenreturn
qreg['foobr']('ooo its an arg', 'oh look another arg')
My favorite way to implement this is with decorators. I used this to make a dispatch table for reading objects from a MySQL database.
(Yes I know I should be using UserDict below. You should too and don’t subclass dict like I did.)
class FuncRegistry(dict): """Creates a registry of hashable objects to function mappings.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def register_for(self, key: Hashable) -> Callable: """Decorator to register functions in the registry. Parameters key: Hashable The key which should point to this function Returns: Callable Returns a decorator that registers the function to the key""" def decorator(fn: Callable) -> Callable: self[key] = fn return fn return decorator qreg = FuncRegistry() @qreg.register_for('foobr') def handle_foobr(arg1, arg2): # do something here then return qreg['foobr']('ooo its an arg', 'oh look another arg')
edit: formatting