Skip to content

Plugin Architecture

Medium ~50 min

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. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

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.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic