this post was submitted on 29 Aug 2023
33 points (100.0% liked)

Python

6405 readers
25 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

๐Ÿ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

๐Ÿ Python project:
๐Ÿ’“ Python Community:
โœจ Python Ecosystem:
๐ŸŒŒ Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 2 points 1 year ago* (last edited 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