In this lesson, you will learn how to create a plugin-style architecture where functions automatically add themselves to a central registry the moment they are defined.
The Problem: Manual Maintenance
In many systems, you might have a collection of handlers, commands, or data processors. Normally, adding a new feature requires two steps: writing the function and then manually adding it to a master dictionary or list. This is error-prone, as it’s easy to forget to register a new component, leading to "missing functionality" bugs.
The Solution: Decorator-Based Registration
We can eliminate this manual step by using a decorator. Because a decorator executes at the time of function definition, it is the perfect place to register that function into a central container.
Consider a system designed to handle different file types:
# The central registry
PLUGIN_REGISTRY = {}
def register_plugin(name):
def decorator(func):
# Automatically add the function to our dictionary
PLUGIN_REGISTRY[name] = func
return func
return decorator
@register_plugin("csv")
def process_csv(data):
return f"Processing CSV: {data}"
@register_plugin("json")
def process_json(data):
return f"Processing JSON: {data}"
# Usage
print(PLUGIN_REGISTRY)
# Output: {'csv': <function process_csv at ...>, 'json': <function process_json at ...>}
Why This Matters
By using this pattern, your architecture becomes "open-closed." The registry system is closed for modification—you don’t need to edit the core logic every time you add a new handler—but it is open for extension. Simply importing a module containing a decorated function is enough to register it, effectively allowing developers to "plug in" new functionality just by defining it.
This technique is a cornerstone of modern Python frameworks, such as web routers or command-line interface tools, where the framework automatically discovers your code without you having to wire it up in a central configuration file.
Key Takeaway: By using a decorator to perform registration at definition time, you decouple the registration logic from the application flow, ensuring new features are automatically discovered and integrated.