Python API¶
Everything public is importable from the pluxeo package. The modules behind it are private.
from pluxeo import (
ContractError, ContractPolicy, default_contract_policy,
DiscoverySource, EntryPointSource, IndexFileSource, NamespacePackageSource,
EnablementPolicy, StaticEnablement,
LifecycleListener,
NamespaceMismatchError, PluginDisabledError, PluginError, PluginNotFoundError,
Plugin, PluginFactory, PluginManager, PluginSpec, PluginState,
hookimpl, hookspec, plugin,
)
PluginManager¶
PluginManager(
namespace: str,
*,
hookspec: type | None = None,
contract: type | None = None,
contract_policy: ContractPolicy | None = None,
load_args: tuple = (),
load_kwargs: Mapping[str, Any] | None = None,
listeners: Sequence[LifecycleListener] = (),
sources: Sequence[DiscoverySource] | None = None,
disabled: Collection[str] = (),
enablement: EnablementPolicy | None = None,
discover: bool = True,
eager: bool = False,
cache: bool = True,
)
Discovers, loads and dispatches to the plugins of one namespace.
| Parameter | Meaning |
|---|---|
namespace |
The namespace, and the entry-point group searched by default. Must be non-empty. |
hookspec |
A class whose @hookspec methods declare the hooks. Without it, pm.hook has no hooks. |
contract |
A @runtime_checkable typing.Protocol every plugin must satisfy. |
contract_policy |
How to react to a non-conforming plugin. Default: default_contract_policy. |
load_args, load_kwargs |
Passed to every plugin's load(). |
listeners |
Objects notified of lifecycle events (LifecycleListener). |
sources |
Where plugins are discovered. Default: [EntryPointSource()]. |
disabled |
Names of plugins to leave out. Ignored when enablement is given. |
enablement |
A policy deciding which plugins are enabled. Default: StaticEnablement(disabled). |
discover |
Run the sources at construction. False for imperative registration only. |
eager |
Call load_all() at construction. |
cache |
Keep one instance and one load result per plugin. False: every load() creates a new instance. |
Attributes¶
namespace- The manager's namespace.
hook- The hook relay.
pm.hook.<name>(**kwargs)calls the hook synchronously;await pm.hook.<name>.aio(**kwargs)andawait pm.hook.<name>.aio_gather(**kwargs)call it asynchronously (Async Hooks). RaisesAttributeErrorfor any name when the manager has no hookspec.
Registration¶
register(obj) -> PluginSpec- Add a plugin.
objis aPluginsubclass (instantiated by calling it with no arguments), aPlugininstance (used as is), a function decorated with@plugin, or aPluginSpec. Replaces any plugin of the same name. RaisesNamespaceMismatchErrorif the plugin's namespace differs from the manager's,ValueErrorif a class or instance lacks a namespace or name,TypeErrorfor anything else.
Loading¶
load(name) -> Any- Load one plugin and return its load result. In order: if it is already loaded and caching is on, return the cached result; check the plugin is enabled; instantiate it through its factory; check the contract; load its
requiresfirst; callshould_load(); callload(*load_args, **load_kwargs); ifload()is a generator, run it to itsyieldand keep it for teardown; register its hooks. Exceptions propagate:PluginNotFoundError,PluginDisabledError,ContractError,PluginError, or whatever the plugin raised. A plugin whose own instantiation, contract check,should_load()orload()raised is markedERRORED. load_all() -> list[Any]- Load every registered plugin, in name order, and return their load results in that order. Plugins that are disabled or decline to load are skipped; plugins that fail are marked
ERROREDand skipped. Never raises for a plugin's failure. unload(name) -> None- The inverse of
load(). First unloads the loaded plugins that requirename, latest loaded first. Then removes the plugin from dispatch, runs the code after itsload()generator'syieldif any, forgets the instance, the load result and any error, and returns the plugin toDISCOVERED. Propagates an exception raised by the cleanup. RaisesPluginNotFoundErrorfor an unknown name. refresh() -> None- Unload every loaded plugin, in reverse load order (a cleanup that raises is turned into a warning), forget every plugin, including those registered with
register(), and run the sources again ifdiscoveris true.
Enablement¶
is_enabled(name) -> bool- False if the host disabled the plugin with
disable(); otherwise the enablement policy's answer. disable(name) -> None- Take the plugin out of dispatch and mark it
DISABLEDif it was loaded; prevent it from loading if it was not. The instance stays alive and no cleanup runs. RaisesPluginNotFoundErrorfor an unknown name. enable(name) -> None- Undo
disable(). A plugin that was loaded before being disabled returns to dispatch and toLOADEDwithout runningload()again. RaisesPluginNotFoundErrorfor an unknown name.
Introspection¶
names() -> list[str]- The registered plugin names, sorted.
state(name) -> PluginState- The plugin's current state. Raises
PluginNotFoundErrorfor an unknown name. error(name) -> BaseException | None- The exception that put the plugin in
ERRORED, orNone. Cleared when the plugin loads successfully or is unloaded. RaisesPluginNotFoundErrorfor an unknown name.
Plugin¶
class Plugin:
namespace: ClassVar[str] = ""
name: ClassVar[str] = ""
requires: tuple[str, ...] = ()
def should_load(self) -> bool: ... # default: True
def load(self, *args, **kwargs) -> Any: ... # default: returns None
Base class for plugins. Subclasses set namespace and name. requires names plugins of the same namespace to load first; it may be set per instance. load() may return a value, or be a generator that yields exactly once: the yielded value is the load result and the code after the yield runs on unload().
plugin¶
plugin(
namespace: str,
name: str | None = None,
*,
should_load: bool | Callable[[], bool] | None = None,
requires: tuple[str, ...] = (),
)
Decorator turning a function into a plugin whose load() calls the function. name defaults to the function's name. Returns the function unchanged, with a __pluginspec__ attribute that register() and the discovery sources read.
PluginSpec¶
What the manager knows about a plugin before loading it: its identity and how to create it. Discovery sources produce specs; factory() imports the plugin's code and returns an instance. Every plugin instance is created by calling its spec's factory. PluginFactory is the type alias for factory.
PluginState¶
Enum: DISCOVERED, INSTANTIATED, LOADED, DISABLED, ERRORED. See Errors and Lifecycle Events.
hookspec, hookimpl¶
Pluggy's HookspecMarker and HookimplMarker, with the project name "pluxeo". Use them bare (@hookspec, @hookimpl) or with options: @hookspec(firstresult=True); @hookimpl(tryfirst=True), @hookimpl(trylast=True), @hookimpl(wrapper=True). See Hooks.
Discovery sources¶
DiscoverySource- Protocol:
find(namespace: str) -> Iterable[PluginSpec]. EntryPointSource()- Entry points of the group named after the namespace. Imports nothing until a plugin is loaded. The default.
IndexFileSource(path: str | Path)- A JSON index written by
pluxeo index:{"namespace": {"name": "module:attr"}}. Imports nothing until a plugin is loaded. NamespacePackageSource(package: str)- The
Pluginsubclasses and@pluginfunctions of the given namespace found in the direct submodules ofpackage. Imports every submodule when the manager discovers.
Enablement¶
EnablementPolicy- Protocol:
is_enabled(namespace: str, name: str) -> bool. StaticEnablement(disabled: Collection[str] = ())- Enables every plugin except the named ones. The default policy.
Contracts¶
ContractPolicy(*, strict: bool = True)validate(plugin, contract)checksisinstance(plugin, contract). Strict: raisesContractError. Lenient: issues a warning. RaisesContractErrorif the contract is not runtime-checkable.strictis a plain attribute and may be changed at any time.default_contract_policy- The
ContractPolicy(strict=True)used by managers created withoutcontract_policy=.
LifecycleListener¶
Protocol. Implement any subset; the manager calls only the methods a listener has. Exceptions raised by a listener become warnings.
class LifecycleListener(Protocol):
def on_resolve_after(self, spec: PluginSpec) -> None: ...
def on_resolve_error(self, spec: PluginSpec, exc: BaseException) -> None: ... # not called yet
def on_init_after(self, spec: PluginSpec, plugin: Plugin) -> None: ...
def on_init_error(self, spec: PluginSpec, exc: BaseException) -> None: ...
def on_load_before(self, spec: PluginSpec, plugin: Plugin) -> None: ...
def on_load_after(self, spec: PluginSpec, plugin: Plugin, result: Any) -> None: ...
def on_load_error(self, spec: PluginSpec, plugin: Plugin | None, exc: BaseException) -> None: ...
Exceptions¶
| Exception | Base | Raised when |
|---|---|---|
PluginError |
Exception |
base class; also dependency cycles and generators that do not yield exactly once |
PluginNotFoundError |
PluginError |
no plugin of that name is registered |
PluginDisabledError |
PluginError |
the plugin is disabled, or declined in should_load() |
NamespaceMismatchError |
PluginError |
a plugin's namespace differs from its manager's |
ContractError |
PluginError |
a plugin fails its contract, or the contract is not runtime-checkable |