Registering handlers without having to import

Viewed 26

I have a growing list of Todo tasks in my application that on completion need different documents created on them. To generalize the workflow on every task I have written a TodoDocumentCreator class.

class TodoDocumentCreator:
    def __init__(self):
        self.creators = {}

    def register_for_todo(self, todo_name):
        if todo_name in self.creators:
            raise CreatorMethodAlreadyExists(duty_slug)

        def wrapper(func):
            self.creators[todo_name] = func
            return func

        return wrapper

    def execute(
        self,
        todo: Todo,
        **kwargs
    ):
        method = self.creators[todo.name]
        return method(**kwargs)

document_creator = TodoDocumentCreator()

As you can see my plan is to register functions for different types of todos. On completion of a todo I then want to run document_creator.execute() and run the todo specific document creation function identified by the name of the todo. But if I attempt this like so:

@document_creator.register_for_duty(todo_name="stromsteueranmeldung")
def fill_stromsteueranmeldung_for_company(todo: Todo):
    # some function code

I am forced to explictly import the function in the module TodoDocumentCreator lies in. This of course kind of defeats the purpose of the entire registration pattern, I could just as well write a huge switch pointing at the relevant functions then.

I was hoping for a way to place all my code relating to the todo "stromsteueranmeldung" in one place separated from code specific to other todos and also separate from code describing the general flow of todo handling. Ideally the general structure code does not need to be touched when adding a new handler to the codesource.

Suggestions in the vein of "your pattern is wrong" are explicitly welcome.

0 Answers
Related