simplug 0.5.0__tar.gz → 0.5.2__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
|
[tool.poetry]
|
|
2
2
|
name = "simplug"
|
|
3
|
-
version = "0.5.
|
|
3
|
+
version = "0.5.2"
|
|
4
4
|
description = "A simple plugin system for python with async hooks supported"
|
|
5
5
|
authors = ["pwwang <pwwang@pwwang.com>"]
|
|
6
6
|
license = "MIT"
|
|
@@ -15,7 +15,7 @@ diot = "^0.3"
|
|
|
15
15
|
[tool.poetry.build]
|
|
16
16
|
generate-setup-file = true
|
|
17
17
|
|
|
18
|
-
[tool.poetry.dev
|
|
18
|
+
[tool.poetry.group.dev.dependencies]
|
|
19
19
|
pytest = "^8"
|
|
20
20
|
pytest-cov = "^5"
|
|
21
21
|
setuptools = "^68"
|
|
@@ -38,3 +38,8 @@ filterwarnings = [
|
|
|
38
38
|
[build-system]
|
|
39
39
|
requires = ["poetry>=1.0"]
|
|
40
40
|
build-backend = "poetry.masonry.api"
|
|
41
|
+
|
|
42
|
+
[tool.black]
|
|
43
|
+
line-length = 88
|
|
44
|
+
target-version = ['py39', 'py310', 'py311', 'py312']
|
|
45
|
+
include = '\.pyi?$'
|
|
@@ -8,7 +8,7 @@ install_requires = \
|
|
|
8
8
|
|
|
9
9
|
setup_kwargs = {
|
|
10
10
|
'name': 'simplug',
|
|
11
|
-
'version': '0.5.
|
|
11
|
+
'version': '0.5.2',
|
|
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',
|
|
@@ -12,7 +12,7 @@ from typing import Any, Callable, Dict, Iterable, List, Tuple
|
|
|
12
12
|
|
|
13
13
|
from diot import OrderedDiot
|
|
14
14
|
|
|
15
|
-
__version__ = "0.5.
|
|
15
|
+
__version__ = "0.5.2"
|
|
16
16
|
|
|
17
17
|
SimplugImpl = namedtuple("SimplugImpl", ["impl", "has_self"])
|
|
18
18
|
SimplugImpl.__doc__ = """A namedtuple wrapper for hook implementation.
|
|
@@ -45,6 +45,10 @@ class NoSuchPlugin(SimplugException):
|
|
|
45
45
|
"""When a plugin cannot be imported"""
|
|
46
46
|
|
|
47
47
|
|
|
48
|
+
class ResultError(SimplugException):
|
|
49
|
+
"""When a result is not available or an error occurs while getting it"""
|
|
50
|
+
|
|
51
|
+
|
|
48
52
|
class ResultUnavailableError(SimplugException):
|
|
49
53
|
"""When a result is not available"""
|
|
50
54
|
|
|
@@ -73,6 +77,10 @@ class HookSpecExists(SimplugException):
|
|
|
73
77
|
"""When a hook has already been defined"""
|
|
74
78
|
|
|
75
79
|
|
|
80
|
+
class AsyncImplOnSyncSpecError(SimplugException):
|
|
81
|
+
"""When an async implementation on a sync hook"""
|
|
82
|
+
|
|
83
|
+
|
|
76
84
|
class SyncImplOnAsyncSpecWarning(Warning):
|
|
77
85
|
"""When a sync implementation on an async hook"""
|
|
78
86
|
|
|
@@ -132,17 +140,34 @@ def makecall(call: SimplugImplCall, async_hook: bool = False):
|
|
|
132
140
|
Returns:
|
|
133
141
|
The result of the call
|
|
134
142
|
"""
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
143
|
+
spec_prefix = "[async]" if async_hook else ""
|
|
144
|
+
err_msg = (
|
|
145
|
+
"Error while calling hook implementation, "
|
|
146
|
+
f"plugin={call.plugin}; spec={spec_prefix}{call.impl.__name__}"
|
|
147
|
+
)
|
|
148
|
+
if inspect.iscoroutinefunction(call.impl):
|
|
149
|
+
|
|
150
|
+
async def coro():
|
|
151
|
+
try:
|
|
152
|
+
return await call.impl(*call.args, **call.kwargs)
|
|
153
|
+
except Exception as exc:
|
|
154
|
+
raise ResultError(err_msg) from exc
|
|
138
155
|
|
|
139
|
-
|
|
140
|
-
return out
|
|
156
|
+
return coro()
|
|
141
157
|
|
|
142
|
-
|
|
143
|
-
|
|
158
|
+
try:
|
|
159
|
+
out = call.impl(*call.args, **call.kwargs)
|
|
160
|
+
except Exception as exc:
|
|
161
|
+
raise ResultError(err_msg) from exc
|
|
144
162
|
|
|
145
|
-
|
|
163
|
+
if async_hook:
|
|
164
|
+
|
|
165
|
+
async def coro():
|
|
166
|
+
return out
|
|
167
|
+
|
|
168
|
+
return coro()
|
|
169
|
+
|
|
170
|
+
return out
|
|
146
171
|
|
|
147
172
|
|
|
148
173
|
class SimplugWrapper:
|
|
@@ -178,9 +203,7 @@ class SimplugWrapper:
|
|
|
178
203
|
try:
|
|
179
204
|
self.plugin = import_module(plugin)
|
|
180
205
|
except ImportError as exc:
|
|
181
|
-
raise NoSuchPlugin(plugin).with_traceback(
|
|
182
|
-
exc.__traceback__
|
|
183
|
-
) from None
|
|
206
|
+
raise NoSuchPlugin(plugin).with_traceback(exc.__traceback__) from None
|
|
184
207
|
|
|
185
208
|
elif isinstance(plugin, tuple):
|
|
186
209
|
# plugin load from entrypoint
|
|
@@ -192,9 +215,7 @@ class SimplugWrapper:
|
|
|
192
215
|
|
|
193
216
|
priority = getattr(self.plugin, "priority", None)
|
|
194
217
|
self.priority: Tuple[int, int] = (
|
|
195
|
-
(batch_index, index)
|
|
196
|
-
if priority is None
|
|
197
|
-
else (priority, batch_index)
|
|
218
|
+
(batch_index, index) if priority is None else (priority, batch_index)
|
|
198
219
|
)
|
|
199
220
|
|
|
200
221
|
self.enabled = True # type: bool
|
|
@@ -438,9 +459,7 @@ class SimplugHook:
|
|
|
438
459
|
if hook is not None:
|
|
439
460
|
plugin_args = (plugin.plugin, *args) if hook.has_self else args
|
|
440
461
|
calls.append(
|
|
441
|
-
SimplugImplCall(
|
|
442
|
-
plugin.name, hook.impl, plugin_args, kwargs
|
|
443
|
-
)
|
|
462
|
+
SimplugImplCall(plugin.name, hook.impl, plugin_args, kwargs)
|
|
444
463
|
)
|
|
445
464
|
|
|
446
465
|
return self._get_results(calls, plugin=_plugin)
|
|
@@ -572,9 +591,7 @@ class SimplugHookAsync(SimplugHook):
|
|
|
572
591
|
continue
|
|
573
592
|
|
|
574
593
|
plugin_args = (plugin.plugin, *args) if hook.has_self else args
|
|
575
|
-
calls.append(
|
|
576
|
-
SimplugImplCall(plugin.name, hook.impl, plugin_args, kwargs)
|
|
577
|
-
)
|
|
594
|
+
calls.append(SimplugImplCall(plugin.name, hook.impl, plugin_args, kwargs))
|
|
578
595
|
|
|
579
596
|
return await self._get_results(calls, plugin=_plugin)
|
|
580
597
|
|
|
@@ -611,13 +628,9 @@ class SimplugHooks:
|
|
|
611
628
|
HookSignatureDifferentFromSpec: When the arguments of a hook
|
|
612
629
|
implementation is different from its specification
|
|
613
630
|
"""
|
|
614
|
-
if
|
|
615
|
-
plugin.name in self._registry
|
|
616
|
-
and plugin != self._registry[plugin.name]
|
|
617
|
-
):
|
|
631
|
+
if plugin.name in self._registry and plugin != self._registry[plugin.name]:
|
|
618
632
|
raise PluginRegistered(
|
|
619
|
-
f"Another plugin named {plugin.name} "
|
|
620
|
-
"has already been registered."
|
|
633
|
+
f"Another plugin named {plugin.name} " "has already been registered."
|
|
621
634
|
)
|
|
622
635
|
# check if required hooks implemented
|
|
623
636
|
# and signature
|
|
@@ -625,8 +638,7 @@ class SimplugHooks:
|
|
|
625
638
|
hook = plugin.hook(specname)
|
|
626
639
|
if spec.required and hook is None:
|
|
627
640
|
raise HookRequired(
|
|
628
|
-
f"{specname}, but not implemented "
|
|
629
|
-
f"in plugin {plugin.name}"
|
|
641
|
+
f"{specname}, but not implemented " f"in plugin {plugin.name}"
|
|
630
642
|
)
|
|
631
643
|
if hook is None: # pragma: no cover
|
|
632
644
|
continue
|
|
@@ -657,6 +669,16 @@ class SimplugHooks:
|
|
|
657
669
|
SyncImplOnAsyncSpecWarning,
|
|
658
670
|
)
|
|
659
671
|
|
|
672
|
+
if not isinstance(spec, SimplugHookAsync) and inspect.iscoroutinefunction(
|
|
673
|
+
hook.impl
|
|
674
|
+
):
|
|
675
|
+
raise AsyncImplOnSyncSpecError(
|
|
676
|
+
f"Sync hook {specname!r} should be implemented by "
|
|
677
|
+
f"a sync function, async implementation "
|
|
678
|
+
f"'{hook.impl.__name__}' "
|
|
679
|
+
f"found for plugin '{plugin.name}'"
|
|
680
|
+
)
|
|
681
|
+
|
|
660
682
|
self._registry[plugin.name] = plugin
|
|
661
683
|
|
|
662
684
|
def _sort_registry(self) -> None:
|
|
@@ -684,9 +706,7 @@ class SimplugHooks:
|
|
|
684
706
|
try:
|
|
685
707
|
return self._specs[name]
|
|
686
708
|
except KeyError as exc:
|
|
687
|
-
raise NoSuchHookSpec(name).with_traceback(
|
|
688
|
-
exc.__traceback__
|
|
689
|
-
) from None
|
|
709
|
+
raise NoSuchHookSpec(name).with_traceback(exc.__traceback__) from None
|
|
690
710
|
|
|
691
711
|
|
|
692
712
|
class SimplugContext:
|
|
@@ -698,8 +718,7 @@ class SimplugContext:
|
|
|
698
718
|
self.simplug = simplug
|
|
699
719
|
self.orig_registry = simplug.hooks._registry.copy()
|
|
700
720
|
self.orig_status = {
|
|
701
|
-
name: plugin.enabled
|
|
702
|
-
for name, plugin in self.orig_registry.items()
|
|
721
|
+
name: plugin.enabled for name, plugin in self.orig_registry.items()
|
|
703
722
|
}
|
|
704
723
|
|
|
705
724
|
def _check_plugins(self, plugins: Iterable[Any]) -> bool:
|
|
@@ -870,15 +889,10 @@ class Simplug:
|
|
|
870
889
|
if not raw:
|
|
871
890
|
return self.hooks._registry
|
|
872
891
|
return OrderedDiot(
|
|
873
|
-
[
|
|
874
|
-
(name, plugin.plugin)
|
|
875
|
-
for name, plugin in self.hooks._registry.items()
|
|
876
|
-
]
|
|
892
|
+
[(name, plugin.plugin) for name, plugin in self.hooks._registry.items()]
|
|
877
893
|
)
|
|
878
894
|
|
|
879
|
-
def get_enabled_plugins(
|
|
880
|
-
self, raw: bool = False
|
|
881
|
-
) -> Dict[str, SimplugWrapper]:
|
|
895
|
+
def get_enabled_plugins(self, raw: bool = False) -> Dict[str, SimplugWrapper]:
|
|
882
896
|
"""Get a mapping of all enabled plugins
|
|
883
897
|
|
|
884
898
|
Args:
|
|
@@ -912,15 +926,10 @@ class Simplug:
|
|
|
912
926
|
Returns:
|
|
913
927
|
The names of all enabled plugins
|
|
914
928
|
"""
|
|
915
|
-
return [
|
|
916
|
-
name
|
|
917
|
-
for name, plugin in self.hooks._registry.items()
|
|
918
|
-
if plugin.enabled
|
|
919
|
-
]
|
|
929
|
+
return [name for name, plugin in self.hooks._registry.items() if plugin.enabled]
|
|
920
930
|
|
|
921
931
|
def plugins_context(
|
|
922
|
-
self,
|
|
923
|
-
plugins: Iterable[Any] | None
|
|
932
|
+
self, plugins: Iterable[Any] | None
|
|
924
933
|
) -> SimplugContext | nullcontext:
|
|
925
934
|
"""A context manager with given plugins enabled or disabled
|
|
926
935
|
|
|
File without changes
|
|
File without changes
|