PluginBase
PluginBase is a module for Python that enables the development of flexible plugin systems. It extends the import system to provide a consistent experience for plugins loaded from various sources, allowing applications to incorporate plugins from bundled or custom directories without bypassing the standard Python import mechanism. It offers a distinct approach compared to setuptools-based plugins, focusing on the virtualization and isolation of plugins rather than their distribution via PyPI. The library currently stands at version 1.0.1 and has a stable, albeit infrequent, release cadence, with the latest update in May 2021.
Warnings
- gotcha Plugins loaded via PluginBase must be imported within the context of an active `plugin_source` using a `with` statement. Attempting to import a plugin outside this context will result in an `ImportError` with a descriptive message.
- gotcha PluginBase provides a system for virtualizing and loading plugins from arbitrary paths, but it is not designed for distributing plugins via PyPI like setuptools entry points. These two approaches solve different problems and are architecturally incompatible.
- gotcha Be aware that the name 'PluginBase' is common across various ecosystems (e.g., Microsoft Dataverse, Tekla, Shopware, and other Python projects). Ensure you are importing and using the `pluginbase` library by Armin Ronacher (mitsuhiko/pluginbase on GitHub) when targeting this specific Python library, as other 'PluginBase' classes will have different APIs and functionalities.
Install
-
pip install pluginbase
Imports
- PluginBase
from pluginbase import PluginBase
Quickstart
from pluginbase import PluginBase
import os
# Define a pseudo-package for your plugins
plugin_base = PluginBase(package='my_app.plugins')
# Define a source for your plugins, specifying search paths
# In a real app, this might be a configurable path or a directory next to your main script.
plugin_dir = os.path.join(os.path.dirname(__file__), 'plugins')
os.makedirs(plugin_dir, exist_ok=True)
# Create a dummy plugin file for demonstration
with open(os.path.join(plugin_dir, 'my_plugin.py'), 'w') as f:
f.write('def greet():\n return "Hello from my_plugin!"')
plugin_source = plugin_base.make_plugin_source(
searchpath=[plugin_dir]
)
# To import a plugin, activate the plugin source using a 'with' statement
with plugin_source:
from my_app.plugins import my_plugin
print(my_plugin.greet())
# Alternatively, load a plugin programmatically
my_other_plugin = plugin_source.load_plugin('my_plugin')
print(my_other_plugin.greet())