Full answer
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:
['broken', 'csv']
1,pen | 2,ink
exporter 'broken' failed: plugin bug
no exporter for pdfThe 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:
[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.
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