Plugin Architecture
What you'll build
A plugin loader that discovers plugins from a directory, validates their interface, and registers them — the pattern behind pytest, Flask, and many tools.
Goals
- Dynamically import modules with importlib
- Define a plugin protocol (base class or Protocol)
- Discover plugins from a directory or entry points
- Handle plugin loading errors gracefully
Prerequisites
- Classes and inheritance
- Modules and imports
- Exception handling
Steps
- 1
Define the plugin interface
Decide what a plugin looks like: an abstract base class with a name property and a run() method, or a Protocol. Document the contract. Acceptance: a plugin author knows exactly what to implement.
Hint
An ABC with @abstractmethod enforces the interface at instantiation time; a Protocol is structural (duck-typed).
- 2
Write the plugin loader
Use importlib to dynamically import .py files from a plugins/ directory. For each module, look for a Plugin class (or a register() function) and instantiate it. Acceptance: plugins in the directory are loaded.
Hint
Use pathlib to list .py files, importlib.import_module to load each, and getattr to find the Plugin class.
- 3
Add validation and error handling
Validate that each loaded plugin implements the required interface. Skip plugins that fail to import or validate, logging a warning instead of crashing. Acceptance: one bad plugin doesn't break the others.
Hint
Use issubclass to check the interface, and try/except around the import to catch syntax errors and missing dependencies.
- 4
Register and execute plugins
Store loaded plugins in a registry (dict by name). Add a run_all() method that calls each plugin's run() in turn, collecting results. Acceptance: run_all() executes all valid plugins and returns their results.
Hint
Catch exceptions per-plugin in run_all so one failing plugin doesn't stop the rest.
- 5
Test with sample plugins
Create 3 plugins: a hello plugin, a math plugin, and a broken plugin (syntax error). Run the loader and confirm the first two load and run, while the broken one is skipped with a warning. Acceptance: the system is resilient to bad plugins.
Hint
This resilience is what makes plugin systems practical in production — users can install third-party plugins without breaking the app.
Try it yourself
What you learned
You built a plugin architecture — the extensibility pattern behind pytest, Flask, Jupyter, and many CLI tools. Dynamic imports and interface validation are the core techniques.
Related Resources
Related Lessons
- Modules
importlib enables dynamic module loading.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.