simplug 0.3.2__tar.gz → 0.4.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: simplug
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.1
|
|
4
4
|
Summary: A simple plugin system for python with async hooks supported
|
|
5
5
|
Home-page: https://github.com/pwwang/simplug
|
|
6
6
|
License: MIT
|
|
@@ -13,6 +13,7 @@ Classifier: Programming Language :: Python :: 3.8
|
|
|
13
13
|
Classifier: Programming Language :: Python :: 3.9
|
|
14
14
|
Classifier: Programming Language :: Python :: 3.10
|
|
15
15
|
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
17
|
Requires-Dist: diot (>=0.2,<0.3)
|
|
17
18
|
Project-URL: Repository, https://github.com/pwwang/simplug
|
|
18
19
|
Description-Content-Type: text/markdown
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "simplug"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.4.1"
|
|
4
4
|
description = "A simple plugin system for python with async hooks supported"
|
|
5
5
|
authors = ["pwwang <pwwang@pwwang.com>"]
|
|
6
6
|
license = "MIT"
|
|
@@ -35,5 +35,5 @@ filterwarnings = [
|
|
|
35
35
|
]
|
|
36
36
|
|
|
37
37
|
[build-system]
|
|
38
|
-
requires = ["poetry>=0
|
|
38
|
+
requires = ["poetry>=1.0"]
|
|
39
39
|
build-backend = "poetry.masonry.api"
|
|
@@ -8,7 +8,7 @@ install_requires = \
|
|
|
8
8
|
|
|
9
9
|
setup_kwargs = {
|
|
10
10
|
'name': 'simplug',
|
|
11
|
-
'version': '0.
|
|
11
|
+
'version': '0.4.1',
|
|
12
12
|
'description': 'A simple plugin system for python with async hooks supported',
|
|
13
13
|
'long_description': '# simplug\n\nA simple plugin system for python with async hooks supported\n\n## Installation\n\n```shell\npip install -U simplug\n```\n\n## Examples\n\n### A toy example\n\n```python\nfrom simplug import Simplug\n\nsimplug = Simplug(\'project\')\n\nclass MySpec:\n """A hook specification namespace."""\n\n @simplug.spec\n def myhook(self, arg1, arg2):\n """My special little hook that you can customize."""\n\nclass Plugin_1:\n """A hook implementation namespace."""\n\n @simplug.impl\n def myhook(self, arg1, arg2):\n print("inside Plugin_1.myhook()")\n return arg1 + arg2\n\nclass Plugin_2:\n """A 2nd hook implementation namespace."""\n\n @simplug.impl\n def myhook(self, arg1, arg2):\n print("inside Plugin_2.myhook()")\n return arg1 - arg2\n\nsimplug.register(Plugin_1, Plugin_2)\nresults = simplug.hooks.myhook(arg1=1, arg2=2)\nprint(results)\n```\n\n```shell\ninside Plugin_1.myhook()\ninside Plugin_2.myhook()\n[3, -1]\n```\n\nNote that the hooks are executed in the order the plugins are registered. This is different from `pluggy`.\n\n### A complete example\n\nSee `examples/complete/`.\n\nRunning `python -m examples.complete` gets us:\n\n```shell\nYour food. Enjoy some egg, egg, egg, salt, pepper, egg, egg\nSome condiments? We have pickled walnuts, steak sauce, mushy peas, mint sauce\n```\n\nAfter install the plugin:\n\n```shell\n> pip install --editable examples.complete.plugin\n> python -m examples.complete # run again\n```\n\n```shell\nYour food. Enjoy some egg, egg, egg, salt, pepper, egg, egg, lovely spam, wonderous spam\nSome condiments? We have pickled walnuts, mushy peas, mint sauce, spam sauce\nNow this is what I call a condiments tray!\n```\n\n## Usage\n\n### Definition of hooks\n\nHooks are specified and implemented by decorating the functions with `simplug.spec` and `simplug.impl` respectively.\n\n`simplug` is initialized by:\n\n```python\nsimplug = Simplug(\'project\')\n```\n\nThe `\'project\'` is a unique name to mark the project, which makes sure `Simplug(\'project\')` get the same instance each time.\n\nNote that if `simplug` is initialized without `project`, then a name is generated automatically as such `project-0`, `project-1`, etc.\n\nHook specification is marked by `simplug.spec`:\n\n```python\nsimplug = Simplug(\'project\')\n\n@simplug.spec\ndef setup(args):\n ...\n```\n\n`simplug.spec` can take some arguments:\n\n- `required`: Whether this hook is required to be implemented in plugins\n- `result`: An enumerator to specify the way to collec the results.\n - `SimplugResult.ALL`: Collect all results from all plugins\n - `SimplugResult.ALL_AVAILS`: Get all the results from the hook, as a list, not including `None`s\n - `SimplugResult.ALL_FIRST`: Executing all implementations and get the first result\n - `SimplugResult.ALL_LAST`: Executing all implementations and get the last result\n - `SimplugResult.TRY_ALL_FIRST`: Executing all implementations and get the first result, if no result is returned, return `None`\n - `SimplugResult.TRY_ALL_LAST`: Executing all implementations and get the last result, if no result is returned, return `None`\n - `SimplugResult.ALL_FIRST_AVAIL`: Executing all implementations and get the first non-`None` result\n - `SimplugResult.ALL_LAST_AVAIL`: Executing all implementations and get the last non-`None` result\n - `SimplugResult.TRY_ALL_FIRST_AVAIL`: Executing all implementations and get the first non-`None` result, if no result is returned, return `None`\n - `SimplugResult.TRY_ALL_LAST_AVAIL`: Executing all implementations and get the last non-`None` result, if no result is returned, return `None`\n - `SimplugResult.FIRST`: Get the first result, don\'t execute other implementations\n - `SimplugResult.LAST`: Get the last result, don\'t execute other implementations\n - `SimplugResult.TRY_FIRST`: Get the first result, don\'t execute other implementations, if no result is returned, return `None`\n - `SimplugResult.TRY_LAST`: Get the last result, don\'t execute other implementations, if no result is returned, return `None`\n - `SimplugResult.FIRST_AVAIL`: Get the first non-`None` result, don\'t execute other implementations\n - `SimplugResult.LAST_AVAIL`: Get the last non-`None` result, don\'t execute other implementations\n - `SimplugResult.TRY_FIRST_AVAIL`: Get the first non-`None` result, don\'t execute other implementations, if no result is returned, return `None`\n - `SimplugResult.TRY_LAST_AVAIL`: Get the last non-`None` result, don\'t execute other implementations, if no result is returned, return `None`\n - `SimplugResult.SINGLE`: Get the result from a single implementation\n - `SimplugResult.TRY_SINGLE`: Get the result from a single implementation, if no result is returned, return `None`\n - A callable to collect the result, take `calls` as the argument, a 3-element tuple with first element as the implementation, second element as the positional arguments, and third element as the keyword arguments.\n\nHook implementation is marked by `simplug.impl`, which takes no additional arguments.\n\nThe name of the function has to match the name of the function by `simplug.spec`. And the signatures of the specification function and the implementation function have to be the same in terms of names. This means you can specify default values in the specification function, but you don\'t have to write the default values in the implementation function.\n\nNote that default values in implementation functions will be ignored.\n\nAlso note if a hook specification is under a namespace, it can take `self` as argument. However, this argument will be ignored while the hook is being called (`self` will be `None`, and you still have to specify it in the function definition).\n\n### Loading plugins from setuptools entrypoint\n\nYou have to call `simplug.load_entrypoints(group)` after the hook specifications are defined to load the plugins registered by setuptools entrypoint. If `group` is not given, the project name will be used.\n\n### The plugin registry\n\nThe plugins are registered by `simplug.register(*plugins)`. Each plugin of `plugins` can be either a python object or a str denoting a module that can be imported by `importlib.import_module`.\n\nThe python object must have an attribute `name`, `__name__` or `__class.__name__` for `simplug` to determine the name of the plugin. If the plugin name is determined from `__name__` or `__class__.__name__`, it will be lowercased.\n\nIf a plugin is loaded from setuptools entrypoint, then the entrypoint name will be used (no matter what name is defined inside the plugin)\n\nYou can enable or disable a plugin temporarily after registration by:\n\n```python\nsimplug.disable(\'plugin_name\')\nsimplug.enable(\'plugin_name\')\n```\n\nYou can use following methods to inspect the plugin registry:\n\n- `simplug.get_plugin`: Get the plugin by name\n- `simplug.get_all_plugins`: Get a dictionary of name-plugin mappings of all plugins\n- `simplug.get_all_plugin_names`: Get the names of all plugins, in the order it will be executed.\n- `simplug.get_enabled_plugins`: Get a dictionary of name-plugin mappings of all enabled plugins\n- `simplug.get_enabled_plugin_names`: Get the names of all enabled plugins, in the order it will be executed.\n\n### Calling hooks\n\nHooks are call by `simplug.hooks.<hook_name>(<arguments>)` and results are collected based on the `result` argument passed in `simplug.spec` when defining hooks.\n\n### Async hooks\n\nIt makes no big difference to define an async hook:\n\n```python\n@simplug.spec\nasync def async_hook(arg):\n ...\n\n# to supress warnings for sync implementation\n@simplug.spec(warn_sync_impl_on_async=False)\nasync def async_hook(arg):\n ...\n```\n\nOne can implement this hook in either an async or a sync way. However, when implementing it in a sync way, a warning will be raised. To suppress the warning, one can pass a `False` value of argument `warn_sync_impl_on_async` to `simplug.spec`.\n\nTo call the async hooks (`simplug.hooks.async_hook(arg)`), you will just need to call it like any other async functions (using `asyncio.run`, for example)\n\n## API\n\nhttps://pwwang.github.io/simplug/\n',
|
|
14
14
|
'author': 'pwwang',
|
|
@@ -1,24 +1,18 @@
|
|
|
1
1
|
"""A simple entrypoint-free plugin system for python"""
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
|
+
import sys
|
|
4
5
|
import inspect
|
|
5
6
|
import warnings
|
|
6
7
|
from collections import namedtuple
|
|
8
|
+
from contextlib import nullcontext
|
|
7
9
|
from enum import Enum
|
|
8
10
|
from importlib import import_module, metadata
|
|
9
|
-
from typing import
|
|
10
|
-
Any,
|
|
11
|
-
Callable,
|
|
12
|
-
Dict,
|
|
13
|
-
Iterable,
|
|
14
|
-
List,
|
|
15
|
-
Optional,
|
|
16
|
-
Tuple,
|
|
17
|
-
)
|
|
11
|
+
from typing import Any, Callable, Dict, Iterable, List, Tuple
|
|
18
12
|
|
|
19
13
|
from diot import OrderedDiot
|
|
20
14
|
|
|
21
|
-
__version__ = "0.
|
|
15
|
+
__version__ = "0.4.1"
|
|
22
16
|
|
|
23
17
|
SimplugImpl = namedtuple("SimplugImpl", ["impl", "has_self"])
|
|
24
18
|
SimplugImpl.__doc__ = """A namedtuple wrapper for hook implementation.
|
|
@@ -206,7 +200,7 @@ class SimplugWrapper:
|
|
|
206
200
|
self.enabled = True # type: bool
|
|
207
201
|
|
|
208
202
|
@property
|
|
209
|
-
def version(self) ->
|
|
203
|
+
def version(self) -> str | None:
|
|
210
204
|
"""Try to get the version of the plugin.
|
|
211
205
|
|
|
212
206
|
If the attribute `version` is definied, use it. Otherwise, try to check
|
|
@@ -266,7 +260,7 @@ class SimplugWrapper:
|
|
|
266
260
|
"""Disable this plugin"""
|
|
267
261
|
self.enabled = False
|
|
268
262
|
|
|
269
|
-
def hook(self, name: str) ->
|
|
263
|
+
def hook(self, name: str) -> SimplugImpl | None:
|
|
270
264
|
"""Get the hook implementation of this plugin by name
|
|
271
265
|
|
|
272
266
|
Args:
|
|
@@ -602,9 +596,9 @@ class SimplugHooks:
|
|
|
602
596
|
|
|
603
597
|
def __init__(self):
|
|
604
598
|
|
|
605
|
-
self._registry = OrderedDiot()
|
|
606
|
-
self._specs = {}
|
|
607
|
-
self._registry_sorted = False
|
|
599
|
+
self._registry = OrderedDiot()
|
|
600
|
+
self._specs = {}
|
|
601
|
+
self._registry_sorted = False
|
|
608
602
|
|
|
609
603
|
def _register(self, plugin: SimplugWrapper) -> None:
|
|
610
604
|
"""Register a plugin (already wrapped by SimplugWrapper)
|
|
@@ -698,82 +692,68 @@ class SimplugHooks:
|
|
|
698
692
|
class SimplugContext:
|
|
699
693
|
"""The context manager for enabling or disabling a set of plugins"""
|
|
700
694
|
|
|
701
|
-
def __init__(self, simplug: "Simplug", plugins:
|
|
695
|
+
def __init__(self, simplug: "Simplug", plugins: Iterable[Any]):
|
|
696
|
+
self.only = self._check_plugins(plugins)
|
|
702
697
|
self.plugins = plugins
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
698
|
+
self.simplug = simplug
|
|
699
|
+
self.orig_registry = simplug.hooks._registry.copy()
|
|
700
|
+
self.orig_status = {
|
|
701
|
+
name: plugin.enabled
|
|
702
|
+
for name, plugin in self.orig_registry.items()
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
def _check_plugins(self, plugins: Iterable[Any]) -> bool:
|
|
706
|
+
"""Check if the given plugins are valid and if all are only mode
|
|
707
|
+
(without prefixes) return True"""
|
|
708
|
+
onlys = [
|
|
709
|
+
isinstance(plug, str) and not plug.startswith(("+", "-"))
|
|
710
|
+
for plug in plugins
|
|
711
|
+
]
|
|
712
|
+
if all(onlys):
|
|
713
|
+
return True
|
|
714
|
+
if any(onlys):
|
|
715
|
+
raise SimplugException(
|
|
716
|
+
"The plugins should be all with prefixes (+, -) or without."
|
|
717
|
+
)
|
|
718
|
+
return False
|
|
719
|
+
|
|
720
|
+
def _raise(self, exc: Exception):
|
|
721
|
+
"""Raise the exception and restore the original status"""
|
|
722
|
+
self.__exit__(*sys.exc_info())
|
|
723
|
+
raise exc
|
|
710
724
|
|
|
711
725
|
def __enter__(self):
|
|
712
|
-
if self.
|
|
713
|
-
|
|
714
|
-
|
|
726
|
+
if self.only:
|
|
727
|
+
for plugin in self.orig_registry.values():
|
|
728
|
+
plugin.disable()
|
|
729
|
+
|
|
715
730
|
# raw
|
|
716
|
-
orig_names = list(orig_registry
|
|
717
|
-
orig_raws = [plugin.plugin for plugin in orig_registry.values()]
|
|
731
|
+
orig_names = list(self.orig_registry)
|
|
732
|
+
orig_raws = [plugin.plugin for plugin in self.orig_registry.values()]
|
|
718
733
|
|
|
719
734
|
for plugin in self.plugins:
|
|
720
|
-
if
|
|
721
|
-
orig_registry[plugin].enable()
|
|
722
|
-
del orig_registry[plugin]
|
|
723
|
-
elif plugin in orig_registry.values():
|
|
735
|
+
if plugin in self.orig_registry.values():
|
|
724
736
|
plugin.enable()
|
|
725
|
-
del orig_registry[plugin.name]
|
|
726
737
|
elif plugin in orig_raws:
|
|
727
738
|
name = orig_names[orig_raws.index(plugin)]
|
|
728
|
-
orig_registry[name].enable()
|
|
729
|
-
|
|
730
|
-
else:
|
|
739
|
+
self.orig_registry[name].enable()
|
|
740
|
+
elif not isinstance(plugin, str):
|
|
731
741
|
self.simplug.register(plugin)
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
742
|
+
elif plugin.startswith("-"):
|
|
743
|
+
if plugin[1:] in self.orig_registry:
|
|
744
|
+
self.orig_registry[plugin[1:]].disable()
|
|
745
|
+
else:
|
|
746
|
+
plugin = plugin[1:] if plugin.startswith("+") else plugin
|
|
747
|
+
if plugin not in self.orig_registry:
|
|
748
|
+
self._raise(NoSuchPlugin(plugin))
|
|
749
|
+
self.orig_registry[plugin].enable()
|
|
735
750
|
|
|
736
751
|
def __exit__(self, *exc):
|
|
737
|
-
if self.plugins is None:
|
|
738
|
-
return
|
|
739
752
|
self.simplug.hooks._registry = self.orig_registry
|
|
740
753
|
for name, status in self.orig_status.items():
|
|
741
754
|
self.simplug.hooks._registry[name].enabled = status
|
|
742
755
|
|
|
743
756
|
|
|
744
|
-
class _SimplugContextOnly(SimplugContext):
|
|
745
|
-
"""The context manager with only given plugins enabled"""
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
class _SimplugContextBut(SimplugContext):
|
|
749
|
-
"""The context manager with only given plugins disabled"""
|
|
750
|
-
|
|
751
|
-
def __enter__(self):
|
|
752
|
-
if self.plugins is None:
|
|
753
|
-
return
|
|
754
|
-
|
|
755
|
-
orig_registry = self.orig_registry.copy()
|
|
756
|
-
# raw
|
|
757
|
-
orig_names = list(orig_registry.keys())
|
|
758
|
-
orig_raws = [plugin.plugin for plugin in orig_registry.values()]
|
|
759
|
-
|
|
760
|
-
for plugin in self.plugins:
|
|
761
|
-
if isinstance(plugin, str) and plugin in orig_registry:
|
|
762
|
-
orig_registry[plugin].disable()
|
|
763
|
-
del orig_registry[plugin]
|
|
764
|
-
elif plugin in orig_registry.values():
|
|
765
|
-
plugin.disable()
|
|
766
|
-
del orig_registry[plugin.name]
|
|
767
|
-
elif plugin in orig_raws:
|
|
768
|
-
name = orig_names[orig_raws.index(plugin)]
|
|
769
|
-
orig_registry[name].disable()
|
|
770
|
-
del orig_registry[name]
|
|
771
|
-
# ignore plugin not existing
|
|
772
|
-
|
|
773
|
-
for plugin in orig_registry.values():
|
|
774
|
-
plugin.enable()
|
|
775
|
-
|
|
776
|
-
|
|
777
757
|
class Simplug:
|
|
778
758
|
"""The plugin manager for simplug
|
|
779
759
|
|
|
@@ -808,7 +788,7 @@ class Simplug:
|
|
|
808
788
|
|
|
809
789
|
def load_entrypoints(
|
|
810
790
|
self,
|
|
811
|
-
group:
|
|
791
|
+
group: str | None = None,
|
|
812
792
|
only: str | Iterable[str] = (),
|
|
813
793
|
) -> None:
|
|
814
794
|
"""Load plugins from setuptools entry_points"""
|
|
@@ -818,9 +798,9 @@ class Simplug:
|
|
|
818
798
|
only = [only]
|
|
819
799
|
|
|
820
800
|
try:
|
|
821
|
-
eps = metadata.entry_points(group=group)
|
|
801
|
+
eps = metadata.entry_points(group=group) # type: ignore
|
|
822
802
|
except TypeError: # pragma: no cover
|
|
823
|
-
eps = metadata.entry_points().get(group, [])
|
|
803
|
+
eps = metadata.entry_points().get(group, []) # type: ignore
|
|
824
804
|
|
|
825
805
|
for ep in eps:
|
|
826
806
|
if only and ep.name not in only:
|
|
@@ -927,35 +907,49 @@ class Simplug:
|
|
|
927
907
|
if plugin.enabled
|
|
928
908
|
]
|
|
929
909
|
|
|
930
|
-
def
|
|
931
|
-
self,
|
|
932
|
-
|
|
933
|
-
|
|
910
|
+
def plugins_context(
|
|
911
|
+
self,
|
|
912
|
+
plugins: Iterable[Any] | None
|
|
913
|
+
) -> SimplugContext | nullcontext:
|
|
914
|
+
"""A context manager with given plugins enabled or disabled
|
|
934
915
|
|
|
935
916
|
Args:
|
|
936
917
|
plugins: The plugin names or plugin objects
|
|
937
918
|
If the given plugin does not exist, register it.
|
|
938
|
-
None to not enable or disable anything
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
919
|
+
None to not enable or disable anything.
|
|
920
|
+
When the context exits, the original status of the plugins
|
|
921
|
+
will be restored.
|
|
922
|
+
You can use `+` or `-` to enable or disable a plugin. If a
|
|
923
|
+
plugin is already enabled or disabled, it will be ignored.
|
|
924
|
+
If a plugin name is given without a prefix, it will be
|
|
925
|
+
enabled and all other plugins will be disabled. If a plugin
|
|
926
|
+
is given as a plugin itself, not a name, it will be regarded as
|
|
927
|
+
`+`.
|
|
928
|
+
|
|
929
|
+
Examples:
|
|
930
|
+
>>> # enabled: plugin1, plugin2; disabled: plugin3
|
|
931
|
+
>>> with simplug.plugins_context(['plugin3']):
|
|
932
|
+
>>> # enabled: plugin3; disabled: plugin1, plugin2
|
|
933
|
+
>>> pass
|
|
934
|
+
>>> # enabled: plugin1, plugin2; disabled: plugin3
|
|
935
|
+
>>> with simplug.plugins_context(['+plugin3']):
|
|
936
|
+
>>> # enabled: plugin1, plugin2, plugin3
|
|
937
|
+
>>> pass
|
|
938
|
+
>>> # enabled: plugin1, plugin2; disabled: plugin3
|
|
939
|
+
>>> with simplug.plugins_context(['-plugin1']):
|
|
940
|
+
>>> # enabled: plugin2; disabled: plugin1, plugin3
|
|
941
|
+
>>> pass
|
|
942
|
+
>>> # enabled: plugin1, plugin2; disabled: plugin3
|
|
943
|
+
>>> with simplug.plugins_context(['-plugin1', '+plugin3']):
|
|
944
|
+
>>> # enabled: plugin2, plugin3; disabled: plugin1
|
|
945
|
+
>>> pass
|
|
954
946
|
|
|
955
947
|
Returns:
|
|
956
948
|
The context manager
|
|
957
949
|
"""
|
|
958
|
-
|
|
950
|
+
if plugins is None:
|
|
951
|
+
return nullcontext()
|
|
952
|
+
return SimplugContext(self, plugins)
|
|
959
953
|
|
|
960
954
|
def enable(self, *names: str) -> None:
|
|
961
955
|
"""Enable plugins by names
|
|
@@ -977,7 +971,7 @@ class Simplug:
|
|
|
977
971
|
|
|
978
972
|
def spec(
|
|
979
973
|
self,
|
|
980
|
-
hook:
|
|
974
|
+
hook: Callable | None = None,
|
|
981
975
|
required: bool = False,
|
|
982
976
|
result: SimplugResult | Callable = SimplugResult.ALL_AVAILS,
|
|
983
977
|
warn_sync_impl_on_async: bool = True,
|
|
File without changes
|
|
File without changes
|