Python API¶
Everything public is importable from the plushy package. The modules behind it are private.
from plushy 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,
)
Each PluginManager owns one namespace: it finds the plugins of that namespace, loads them and calls their hooks.
| Parameter | Meaning |
|---|---|
namespace |
The namespace. It is also the entry-point group searched by default, and 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 that plugins must satisfy. |
contract_policy |
How to react to a non-conforming plugin. Default: default_contract_policy. |
load_args, load_kwargs |
Passed to each 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. With False, load() creates a new instance on each call. |
Attributes¶
namespace- The manager's namespace.
hook- The hook relay.
pm.hook.<name>(**kwargs)calls the hook synchronously.pm.hook.<name>.call_historic(result_callback=None, kwargs=None)calls a historic hook.await pm.hook.<name>.aio(**kwargs)andawait pm.hook.<name>.aio_gather(**kwargs)call it asynchronously (Async Hooks). Without a hookspec, the relay raisesAttributeErrorfor any name.
Any method that takes a plugin name raises PluginNotFoundError when no plugin of that name is registered.
Registration¶
register(obj) -> PluginSpec- Adds a plugin, replacing any plugin of the same name.
objcan be aPluginsubclass (instantiated by calling it with no arguments), aPlugininstance (used as is), a function decorated with@plugin, or aPluginSpec. It raisesNamespaceMismatchErrorif the plugin's namespace differs from the manager's,ValueErrorif a class or instance lacks a namespace or name, andTypeErrorfor anything else.
Loading¶
load(name) -> Any-
Loads one plugin and returns the load result, in these steps:
- If the plugin is already loaded and caching is on, return the cached result.
- Check that the plugin is enabled.
- Instantiate it through the factory, and check the contract.
- Load the plugins it
requires. - Call
should_load(), thenload(*load_args, **load_kwargs). A generatorload()runs up to theyieldand is kept for teardown. - Register the plugin's hooks.
Exceptions propagate:
PluginNotFoundError,PluginDisabledError,ContractError,PluginError, or whatever the plugin raised. When instantiation, the contract check, a requirement,should_load()orload()fails, the plugin is markedERRORED. load_all(*, strict: bool = False) -> list[Any]- Loads the registered plugins, in name order, and returns their load results in that order. Plugins that are disabled or decline to load are skipped; plugins that fail are marked
ERROREDand skipped. Withoutstrict, never raises for a plugin's failure. Withstrict=True, after trying every plugin, raises anExceptionGroupof onePluginErrorper failed plugin, each naming the plugin and chained to its exception. 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 cleanup after theyieldof a generatorload(), forgets the instance, the load result and any error, and returns the plugin toDISCOVERED. Propagates an exception raised by the cleanup. refresh() -> None- Unloads the loaded plugins, in reverse load order (a cleanup that raises is turned into a warning), forgets all plugins, including those registered with
register(), and run the sources again ifdiscoveris true.
Enablement¶
is_enabled(name) -> bool- Returns False if the host disabled the plugin with
disable(). Otherwise, it returns 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. enable(name) -> None- Undo
disable(). A plugin that was loaded when it was disabled returns to dispatch and toLOADEDwithout runningload()again. Any other plugin only becomes loadable again: a plugin that declined inshould_load()staysDISABLED.
Introspection¶
names() -> list[str]- The registered plugin names, sorted.
state(name) -> PluginState- Returns the plugin's current state.
error(name) -> BaseException | None- Returns the exception that put the plugin in
ERRORED, orNone. The exception is forgotten when the plugin loads successfully or is unloaded.
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, ...] = (),
)
This decorator turns a function into a plugin whose load() calls the function. name defaults to the function's name. The decorator 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: the plugin's 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 the spec's factory. The type of factory is exported as PluginFactory.
PluginState¶
Enum: DISCOVERED, INSTANTIATED, LOADED, DISABLED, ERRORED. See Errors and Lifecycle Events.
hookspec, hookimpl¶
Pluggy's HookspecMarker and HookimplMarker, with the project name "plushy". Use them bare (@hookspec, @hookimpl) or with options: @hookspec(firstresult=True), @hookspec(historic=True); @hookimpl(tryfirst=True), @hookimpl(trylast=True), @hookimpl(wrapper=True). See Hooks.
Discovery sources¶
DiscoverySource- Protocol:
find(namespace: str) -> Iterable[PluginSpec]. EntryPointSource()- Reads the entry points of the group named after the namespace, and imports nothing until a plugin is loaded. This is the default source.
IndexFileSource(path: str | Path)- A JSON index written by
plushy index:{"namespace": {"name": "module:attr"}}. Imports nothing until a plugin is loaded. NamespacePackageSource(package: str)- Finds the
Pluginsubclasses and@pluginfunctions of the given namespace in the direct submodules ofpackage, which it imports when the manager discovers.
Enablement¶
EnablementPolicy- Protocol:
is_enabled(namespace: str, name: str) -> bool. StaticEnablement(disabled: Collection[str] = ())- Enables all plugins except the named ones. This is the default policy.
Contracts¶
ContractPolicy(*, strict: bool = True)validate(plugin, contract)checksisinstance(plugin, contract). On failure, a strict policy raisesContractErrorand a lenient one issues a warning. Both raiseContractErrorif the contract is not runtime-checkable.strictis a plain attribute, which may change 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_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 the contract, or the contract is not runtime-checkable |