• Zeusbottom@sh.itjust.works
    link
    fedilink
    English
    arrow-up
    1
    ·
    edit-2
    1 year ago

    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