jeudi 17 septembre 2020

Using a decorator to register functions across different modules

I have a list of functions that will be organized under different modules based on their properties and logic. I want to use a decorator to add them all to a single registry (i.e. a dictionary) so that I can dynamically select the desired function based on their name.

So I'll have the following structure:

# registry.py

REGISTRY = {}

def register_func(func_name):
    def func_decoractor(func):
        REGISTRY[func_name] = func
    return func_decorator

And in another module:

# project_dir/funcA.py

@register_func("foo")
def funcA():
   ...

I keep running into circular imports when I try to use this hierarchy. I'd prefer to not use metaclasses as I want to keep these as functions as opposed to classes. How would I approach this implementation?

Aucun commentaire:

Enregistrer un commentaire