How would you build a decorator-based plugin/registration system, similar to how Flask's @app.route() registers view functions?
Short answer
Have the decorator STORE a reference to the decorated function in a shared registry (a dict or list, often a class attribute or module-level variable) as a SIDE EFFECT, while returning the ORIGINAL function UNCHANGED — the decorator's primary purpose here is registration, not…
Advertisement
AModel answer
Have the decorator STORE a reference to the decorated function in a shared registry (a dict or list, often a class attribute or module-level variable) as a SIDE EFFECT, while returning the ORIGINAL function UNCHANGED — the decorator's primary purpose here is registration, not wrapping/modifying behavior.
routes = {}
def route(path):
def decorator(func):
routes[path] = func # registers the function, but doesn't wrap/modify it
return func # returns the ORIGINAL function, unchanged
return decorator
@route("/users")
def list_users():
return ["Sam", "Alex"]
print(routes["/users"]()) # calls list_users() via the registryReal-world example
Building a lightweight routing system, event handler registry, or plugin discovery mechanism using decorators purely for registration.
Likely follow-ups
- Why does this registration-style decorator return the ORIGINAL function unchanged, unlike a typical wrapping decorator?
Related topics