Contracts¶
A contract states what every plugin of a namespace must provide, as a typing.Protocol. pluxeo checks each plugin against it when the plugin loads, so a plugin missing a method fails at startup, near its cause, rather than the first time some rarely used code path calls the missing method.
Declaring one¶
from typing import Protocol, runtime_checkable
from pluxeo import ContractError, Plugin, PluginManager
@runtime_checkable
class Exporter(Protocol):
format: str
def export(self, rows: list[dict]) -> bytes: ...
class Csv(Plugin):
namespace = "acme.exporters"
name = "csv"
format = "text/csv"
def export(self, rows):
return b"..."
class Broken(Plugin):
namespace = "acme.exporters"
name = "broken" # no format, no export()
pm = PluginManager("acme.exporters", contract=Exporter, discover=False)
pm.register(Csv)
pm.register(Broken)
pm.load("csv")
try:
pm.load("broken")
except ContractError as e:
print(e) # plugin acme.exporters:broken does not satisfy contract Exporter
Plugins do not inherit from the Protocol: conforming is enough. The contract must be decorated with @runtime_checkable; otherwise loading raises ContractError saying so.
What is checked, and when¶
- When: right after the plugin is instantiated, before
should_load()andload()run. A plugin that fails is markedERRORED; inload_all()the others still load. - What: that each member of the Protocol exists on the plugin object. This is Python's
isinstancecheck for runtime-checkable protocols: it does not compare signatures or types.
The real type check is the plugin author's own mypy or pyright run against your published Protocol. pluxeo's check is the backstop for plugins that skipped it.
Hook implementations are checked separately, by Pluggy, when the plugin joins dispatch: an implementation that names an argument its hookspec lacks is rejected. Contracts and hookspecs are complementary. The contract covers the plugin object as a whole, including attributes and methods that are not hooks.
Strict or lenient¶
The default policy is strict: a non-conforming plugin raises ContractError. A lenient policy issues a warning and lets the plugin load:
from pluxeo import ContractPolicy, PluginManager
# Exporter as declared above
pm = PluginManager("acme.exporters", contract=Exporter, contract_policy=ContractPolicy(strict=False))
Managers created without contract_policy= share pluxeo.default_contract_policy, and see changes to it immediately:
import pluxeo
pluxeo.default_contract_policy.strict = False # e.g. in production, from configuration
A common arrangement: strict in tests and CI, so a non-conforming plugin breaks the build; lenient in production, so it is reported without taking the application down.