← Back to Python, page 4

python-0072 · Hard senior

Design a plugin system so third parties can add exporters to an application without changing its code.

Define a small interface (a Protocol or ABC) for exporters, and discover implementations through package entry points (importlib.metadata.entry_points(group='app.exporters')) or a registry populated by __init_subclass__. Load plugins lazily, validate them against the interface, isolate failures so one bad plugin does not break the app, and version the interface.

Full answer
python
class Exporter:
    registry = {}
    def __init_subclass__(cls, fmt, **kw):
        super().__init_subclass__(**kw)
        Exporter.registry[fmt] = cls
    def export(self, rows):
        raise NotImplementedError

class CsvExporter(Exporter, fmt="csv"):
    def export(self, rows):
        return " | ".join(",".join(map(str, r)) for r in rows)

class BrokenExporter(Exporter, fmt="broken"):
    def export(self, rows):
        raise RuntimeError("plugin bug")

def run_export(fmt, rows):
    cls = Exporter.registry.get(fmt)
    if cls is None:
        return f"no exporter for {fmt}"
    try:
        return cls().export(rows)
    except Exception as e:
        return f"exporter {fmt!r} failed: {e}"

rows = [(1, "pen"), (2, "ink")]
print(sorted(Exporter.registry))
print(run_export("csv", rows))
print(run_export("broken", rows))
print(run_export("pdf", rows))

Output:

text
['broken', 'csv']
1,pen | 2,ink
exporter 'broken' failed: plugin bug
no exporter for pdf

The registry version shows the core idea: subclasses register themselves by format name, and the application looks them up without knowing the classes in advance. A broken plugin raises during export, and the application reports it instead of crashing.

For packages installed separately, entry points are the standard mechanism. A plugin package declares, in its pyproject.toml:

toml
[project.entry-points."app.exporters"]
pdf = "app_pdf.exporter:PdfExporter"

and the application runs for ep in entry_points(group="app.exporters"): registry[ep.name] = ep.load(). That snippet needs an installed plugin package, so it was not run here.

Further design points: keep the interface minimal and stable, pass plugins a narrow context object rather than the whole application, document a version and check compatibility at load time, and consider running untrusted plugins in a separate process.

python
class Exporter:
    registry = {}
    def __init_subclass__(cls, fmt, **kw):
        super().__init_subclass__(**kw)
        Exporter.registry[fmt] = cls
    def export(self, rows):
        raise NotImplementedError

class CsvExporter(Exporter, fmt="csv"):
    def export(self, rows):
        return " | ".join(",".join(map(str, r)) for r in rows)

class BrokenExporter(Exporter, fmt="broken"):
    def export(self, rows):
        raise RuntimeError("plugin bug")

def run_export(fmt, rows):
    cls = Exporter.registry.get(fmt)
    if cls is None:
        return f"no exporter for {fmt}"
    try:
        return cls().export(rows)
    except Exception as e:
        return f"exporter {fmt!r} failed: {e}"

rows = [(1, "pen"), (2, "ink")]
print(sorted(Exporter.registry))
print(run_export("csv", rows))
print(run_export("broken", rows))
print(run_export("pdf", rows))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Define a minimal interface
  • Discover via entry points or a registry
  • Load lazily and validate
  • Isolate plugin failures
  • Version the interface

Common mistakes

  • Importing every plugin at startup with no error handling
  • Exposing internal objects to plugins

Follow-ups

  • How would you sandbox untrusted plugins?
  • How does pytest discover its plugins?

Tips

  • Name entry points