simplug 0.5.3__tar.gz → 0.5.4__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.
|
@@ -8,7 +8,7 @@ install_requires = \
|
|
|
8
8
|
|
|
9
9
|
setup_kwargs = {
|
|
10
10
|
'name': 'simplug',
|
|
11
|
-
'version': '0.5.
|
|
11
|
+
'version': '0.5.4',
|
|
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',
|
|
@@ -9,20 +9,64 @@ from collections import namedtuple
|
|
|
9
9
|
from contextlib import nullcontext
|
|
10
10
|
from enum import Enum
|
|
11
11
|
from importlib import import_module, metadata
|
|
12
|
-
from typing import Any, Callable, Dict, Iterable, List, Tuple
|
|
12
|
+
from typing import Any, Callable, Dict, Iterable, List, Tuple, Union, Optional
|
|
13
13
|
|
|
14
14
|
from diot import OrderedDiot
|
|
15
15
|
|
|
16
|
-
__version__ = "0.5.
|
|
16
|
+
__version__ = "0.5.4"
|
|
17
17
|
|
|
18
|
-
SimplugImpl = namedtuple("SimplugImpl", ["impl", "has_self"])
|
|
19
|
-
SimplugImpl.__doc__ = """A namedtuple wrapper for hook implementation.
|
|
20
18
|
|
|
21
|
-
|
|
19
|
+
class SimplugImpl:
|
|
20
|
+
"""A namedtuple wrapper for hook implementation.
|
|
21
|
+
|
|
22
|
+
This is used to mark the method/function to be an implementation of a hook.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
impl: The hook implementation
|
|
26
|
+
has_self: Whether the first argument is `self`
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
__slots__ = ("impl", "has_self")
|
|
30
|
+
|
|
31
|
+
def __init__(self, impl: Callable, has_self: bool):
|
|
32
|
+
self.impl = impl
|
|
33
|
+
self.has_self = has_self
|
|
34
|
+
|
|
35
|
+
def __call__(self, *args: Any, **kwds: Any) -> Any:
|
|
36
|
+
return self.impl(*args, **kwds)
|
|
37
|
+
|
|
38
|
+
def __get__(self, obj: Any, objtype: type | None = None) -> "SimplugImpl":
|
|
39
|
+
"""Descriptor protocol to make this work as a bound method when accessed
|
|
40
|
+
on an instance."""
|
|
41
|
+
if obj is None:
|
|
42
|
+
# When accessed on the class, return the SimplugImpl itself
|
|
43
|
+
return self
|
|
44
|
+
if self.has_self:
|
|
45
|
+
# Return a bound method-like callable that auto-passes the instance
|
|
46
|
+
# but still appears as a SimplugImpl
|
|
47
|
+
class BoundSimplugImpl(SimplugImpl):
|
|
48
|
+
def __init__(self, original_impl: "SimplugImpl", instance: Any) -> None:
|
|
49
|
+
super().__init__(original_impl.impl, original_impl.has_self)
|
|
50
|
+
self.instance = instance
|
|
51
|
+
|
|
52
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
53
|
+
return self.impl(self.instance, *args, **kwargs)
|
|
54
|
+
|
|
55
|
+
def __get__(
|
|
56
|
+
self, obj: Any, objtype: type | None = None
|
|
57
|
+
) -> "SimplugImpl": # pragma: no cover
|
|
58
|
+
# Handle super() calls - when accessed on another instance
|
|
59
|
+
if obj is None:
|
|
60
|
+
return self
|
|
61
|
+
# For super() calls, we want to call with the new instance
|
|
62
|
+
# Create a new bound method for the new instance
|
|
63
|
+
return BoundSimplugImpl(SimplugImpl(self.impl, self.has_self), obj)
|
|
64
|
+
|
|
65
|
+
return BoundSimplugImpl(self, obj)
|
|
66
|
+
else:
|
|
67
|
+
# For non-self methods, still return the original SimplugImpl
|
|
68
|
+
return self
|
|
22
69
|
|
|
23
|
-
Args:
|
|
24
|
-
impl: The hook implementation
|
|
25
|
-
"""
|
|
26
70
|
|
|
27
71
|
SimplugImplCall = namedtuple(
|
|
28
72
|
"SimplugImplCall",
|
|
@@ -93,19 +137,20 @@ class MultipleImplsForSingleResultHookWarning(Warning):
|
|
|
93
137
|
class SimplugResult(Enum):
|
|
94
138
|
"""Way to get the results from the hooks
|
|
95
139
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
140
|
+
Available result types:
|
|
141
|
+
- ALL: Execute all implementations for the hook
|
|
142
|
+
- ALL_AVAILS: Get non-`None` results
|
|
143
|
+
- FIRST: Get the first result, ordered by priority
|
|
144
|
+
Don't execute the other implementations
|
|
145
|
+
- LAST: Get the last result, ordered by priority
|
|
146
|
+
Don't execute the other implementations
|
|
147
|
+
- ALL_FIRST: Get the first result from each implementation and
|
|
148
|
+
execute the other implementations
|
|
149
|
+
- ALL_LAST: Get the last result from each implementation and
|
|
150
|
+
execute the other implementations
|
|
151
|
+
- TRY_*: Return `None` instead of raising `ResultUnavailableError` when
|
|
107
152
|
no result is available
|
|
108
|
-
SINGLE
|
|
153
|
+
- SINGLE: Get the result from a single implementation
|
|
109
154
|
"""
|
|
110
155
|
|
|
111
156
|
# 0b 1 1 1 1111
|
|
@@ -132,11 +177,12 @@ class SimplugResult(Enum):
|
|
|
132
177
|
TRY_SINGLE = 0b100_1010 # 146
|
|
133
178
|
|
|
134
179
|
|
|
135
|
-
def makecall(call: SimplugImplCall, async_hook: bool = False):
|
|
180
|
+
def makecall(call: SimplugImplCall, async_hook: bool = False) -> Any:
|
|
136
181
|
"""Make a call to an implementation and arguments
|
|
137
182
|
|
|
138
183
|
Args:
|
|
139
184
|
call: 3-element tuple of (implementation, args, kwargs)
|
|
185
|
+
async_hook: Whether this is being called from an async hook
|
|
140
186
|
|
|
141
187
|
Returns:
|
|
142
188
|
The result of the call
|
|
@@ -198,7 +244,12 @@ class SimplugWrapper:
|
|
|
198
244
|
imported as a module
|
|
199
245
|
"""
|
|
200
246
|
|
|
201
|
-
|
|
247
|
+
plugin: Any
|
|
248
|
+
_name: Optional[str]
|
|
249
|
+
priority: Tuple[int, int]
|
|
250
|
+
enabled: bool
|
|
251
|
+
|
|
252
|
+
def __init__(self, plugin: Any, batch_index: int, index: int) -> None:
|
|
202
253
|
self.plugin = self._name = None
|
|
203
254
|
if isinstance(plugin, str):
|
|
204
255
|
try:
|
|
@@ -222,7 +273,7 @@ class SimplugWrapper:
|
|
|
222
273
|
self.enabled = True # type: bool
|
|
223
274
|
|
|
224
275
|
@property
|
|
225
|
-
def version(self) -> str
|
|
276
|
+
def version(self) -> Optional[str]:
|
|
226
277
|
"""Try to get the version of the plugin.
|
|
227
278
|
|
|
228
279
|
If the attribute `version` is definied, use it. Otherwise, try to check
|
|
@@ -278,11 +329,11 @@ class SimplugWrapper:
|
|
|
278
329
|
"""Enable this plugin"""
|
|
279
330
|
self.enabled = True
|
|
280
331
|
|
|
281
|
-
def disable(self):
|
|
332
|
+
def disable(self) -> None:
|
|
282
333
|
"""Disable this plugin"""
|
|
283
334
|
self.enabled = False
|
|
284
335
|
|
|
285
|
-
def hook(self, name: str) -> SimplugImpl
|
|
336
|
+
def hook(self, name: str) -> Optional[SimplugImpl]:
|
|
286
337
|
"""Get the hook implementation of this plugin by name
|
|
287
338
|
|
|
288
339
|
Args:
|
|
@@ -322,18 +373,27 @@ class SimplugHook:
|
|
|
322
373
|
spec: The specification of the hook
|
|
323
374
|
required: Whether this hook is required to be implemented
|
|
324
375
|
result: Way to collect the results from the hook
|
|
325
|
-
|
|
326
|
-
|
|
376
|
+
debug: Whether to print debug messages
|
|
377
|
+
warn_sync_impl_on_async: Whether to warn about sync implementations
|
|
378
|
+
on async hooks
|
|
327
379
|
"""
|
|
328
380
|
|
|
381
|
+
simplug_hooks: "SimplugHooks"
|
|
382
|
+
spec: Callable[..., Any]
|
|
383
|
+
name: str
|
|
384
|
+
required: bool
|
|
385
|
+
result: Union[SimplugResult, Callable]
|
|
386
|
+
debug: bool
|
|
387
|
+
warn_sync_impl_on_async: bool
|
|
388
|
+
|
|
329
389
|
def __init__(
|
|
330
390
|
self,
|
|
331
|
-
simplug_hooks: SimplugHooks,
|
|
332
|
-
spec: Callable,
|
|
391
|
+
simplug_hooks: "SimplugHooks",
|
|
392
|
+
spec: Callable[..., Any],
|
|
333
393
|
required: bool,
|
|
334
|
-
result: SimplugResult
|
|
394
|
+
result: Union[SimplugResult, Callable],
|
|
335
395
|
warn_sync_impl_on_async: bool = False,
|
|
336
|
-
):
|
|
396
|
+
) -> None:
|
|
337
397
|
self.simplug_hooks = simplug_hooks
|
|
338
398
|
self.spec = spec
|
|
339
399
|
self.name = spec.__name__
|
|
@@ -342,11 +402,49 @@ class SimplugHook:
|
|
|
342
402
|
self.debug = False
|
|
343
403
|
self.warn_sync_impl_on_async = warn_sync_impl_on_async
|
|
344
404
|
|
|
405
|
+
def _prepare_plugin_args(
|
|
406
|
+
self, plugin: SimplugWrapper, hook: SimplugImpl, args: Tuple[Any, ...]
|
|
407
|
+
) -> Tuple[Any, ...]:
|
|
408
|
+
"""Prepare arguments for calling a plugin hook implementation.
|
|
409
|
+
|
|
410
|
+
Args:
|
|
411
|
+
plugin: The plugin wrapper
|
|
412
|
+
hook: The hook implementation (SimplugImpl)
|
|
413
|
+
args: The original arguments to the hook
|
|
414
|
+
|
|
415
|
+
Returns:
|
|
416
|
+
Tuple of prepared arguments for the hook implementation
|
|
417
|
+
"""
|
|
418
|
+
if not hook.has_self:
|
|
419
|
+
return args
|
|
420
|
+
|
|
421
|
+
self_obj = plugin.plugin
|
|
422
|
+
if inspect.isclass(self_obj):
|
|
423
|
+
# Try to instantiate the class if it has no required parameters
|
|
424
|
+
try:
|
|
425
|
+
sig = inspect.signature(self_obj)
|
|
426
|
+
required_params = [
|
|
427
|
+
p for p in sig.parameters.values()
|
|
428
|
+
if (p.kind in (
|
|
429
|
+
inspect.Parameter.POSITIONAL_ONLY,
|
|
430
|
+
inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
|
431
|
+
) and p.default is inspect.Parameter.empty
|
|
432
|
+
and p.name != "self")
|
|
433
|
+
]
|
|
434
|
+
if not required_params:
|
|
435
|
+
self_obj = self_obj()
|
|
436
|
+
except (TypeError, ValueError): # pragma: no cover
|
|
437
|
+
# More specific exception handling
|
|
438
|
+
# Fallback to passing the class if instantiation fails
|
|
439
|
+
pass
|
|
440
|
+
|
|
441
|
+
return (self_obj, *args)
|
|
442
|
+
|
|
345
443
|
def _get_results(
|
|
346
444
|
self,
|
|
347
445
|
calls: List[SimplugImplCall],
|
|
348
|
-
plugin: str,
|
|
349
|
-
result: SimplugResult
|
|
446
|
+
plugin: Optional[str],
|
|
447
|
+
result: Optional[Union[SimplugResult, Callable, int]] = None,
|
|
350
448
|
) -> Any:
|
|
351
449
|
"""Get the results according to self.result"""
|
|
352
450
|
result = self.result if result is None else result
|
|
@@ -458,7 +556,7 @@ class SimplugHook:
|
|
|
458
556
|
)
|
|
459
557
|
return makecall(calls[-1])
|
|
460
558
|
|
|
461
|
-
def __call__(self, *args, **kwargs):
|
|
559
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
462
560
|
"""Call the hook in your system
|
|
463
561
|
|
|
464
562
|
Args:
|
|
@@ -499,7 +597,7 @@ class SimplugHook:
|
|
|
499
597
|
hook = plugin.hook(self.name)
|
|
500
598
|
|
|
501
599
|
if hook is not None:
|
|
502
|
-
plugin_args = (plugin
|
|
600
|
+
plugin_args = self._prepare_plugin_args(plugin, hook, args)
|
|
503
601
|
if self.debug:
|
|
504
602
|
print(f"[simplug] - Pushing call {plugin.name}.{self.name}")
|
|
505
603
|
|
|
@@ -516,8 +614,8 @@ class SimplugHookAsync(SimplugHook):
|
|
|
516
614
|
async def _get_results(
|
|
517
615
|
self,
|
|
518
616
|
calls: List[SimplugImplCall],
|
|
519
|
-
plugin: str,
|
|
520
|
-
result: SimplugResult
|
|
617
|
+
plugin: Optional[str],
|
|
618
|
+
result: Optional[Union[SimplugResult, Callable, int]] = None,
|
|
521
619
|
) -> Any:
|
|
522
620
|
"""Get the results according to self.result"""
|
|
523
621
|
result = self.result if result is None else result
|
|
@@ -635,7 +733,7 @@ class SimplugHookAsync(SimplugHook):
|
|
|
635
733
|
)
|
|
636
734
|
return await makecall(calls[-1], True)
|
|
637
735
|
|
|
638
|
-
async def __call__(self, *args, **kwargs):
|
|
736
|
+
async def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
639
737
|
"""Call the hook in your system asynchronously
|
|
640
738
|
|
|
641
739
|
Args:
|
|
@@ -677,7 +775,7 @@ class SimplugHookAsync(SimplugHook):
|
|
|
677
775
|
if hook is None: # pragma: no cover
|
|
678
776
|
continue
|
|
679
777
|
|
|
680
|
-
plugin_args = (plugin
|
|
778
|
+
plugin_args = self._prepare_plugin_args(plugin, hook, args)
|
|
681
779
|
if self.debug:
|
|
682
780
|
print(f"[simplug] - Pushing call {plugin.name}.{self.name}")
|
|
683
781
|
calls.append(SimplugImplCall(plugin.name, hook.impl, plugin_args, kwargs))
|
|
@@ -700,10 +798,14 @@ class SimplugHooks:
|
|
|
700
798
|
_registry_sorted: Whether the plugin registry has been sorted already
|
|
701
799
|
"""
|
|
702
800
|
|
|
703
|
-
|
|
801
|
+
_registry: OrderedDiot
|
|
802
|
+
_specs: Dict[str, Union["SimplugHook", "SimplugHookAsync"]]
|
|
803
|
+
_registry_sorted: bool
|
|
804
|
+
|
|
805
|
+
def __init__(self) -> None:
|
|
704
806
|
|
|
705
807
|
self._registry = OrderedDiot()
|
|
706
|
-
self._specs = {}
|
|
808
|
+
self._specs: Dict[str, Union[SimplugHook, SimplugHookAsync]] = {}
|
|
707
809
|
self._registry_sorted = False
|
|
708
810
|
|
|
709
811
|
def _register(self, plugin: SimplugWrapper) -> None:
|
|
@@ -780,7 +882,7 @@ class SimplugHooks:
|
|
|
780
882
|
)
|
|
781
883
|
self._registry_sorted = True
|
|
782
884
|
|
|
783
|
-
def __getattr__(self, name: str) -> "SimplugHook":
|
|
885
|
+
def __getattr__(self, name: str) -> Union["SimplugHook", "SimplugHookAsync"]:
|
|
784
886
|
"""Get the hook by name
|
|
785
887
|
|
|
786
888
|
Args:
|
|
@@ -801,7 +903,13 @@ class SimplugHooks:
|
|
|
801
903
|
class SimplugContext:
|
|
802
904
|
"""The context manager for enabling or disabling a set of plugins"""
|
|
803
905
|
|
|
804
|
-
|
|
906
|
+
only: bool
|
|
907
|
+
plugins: Iterable[Any]
|
|
908
|
+
simplug: "Simplug"
|
|
909
|
+
orig_registry: OrderedDiot
|
|
910
|
+
orig_status: Dict[str, bool]
|
|
911
|
+
|
|
912
|
+
def __init__(self, simplug: "Simplug", plugins: Iterable[Any]) -> None:
|
|
805
913
|
self.only = self._check_plugins(plugins)
|
|
806
914
|
self.plugins = plugins
|
|
807
915
|
self.simplug = simplug
|
|
@@ -825,12 +933,12 @@ class SimplugContext:
|
|
|
825
933
|
)
|
|
826
934
|
return False
|
|
827
935
|
|
|
828
|
-
def _raise(self, exc: Exception):
|
|
936
|
+
def _raise(self, exc: Exception) -> None:
|
|
829
937
|
"""Raise the exception and restore the original status"""
|
|
830
938
|
self.__exit__(*sys.exc_info())
|
|
831
939
|
raise exc
|
|
832
940
|
|
|
833
|
-
def __enter__(self):
|
|
941
|
+
def __enter__(self) -> None:
|
|
834
942
|
if self.only:
|
|
835
943
|
for plugin in self.orig_registry.values():
|
|
836
944
|
plugin.disable()
|
|
@@ -856,7 +964,7 @@ class SimplugContext:
|
|
|
856
964
|
self._raise(NoSuchPlugin(plugin))
|
|
857
965
|
self.orig_registry[plugin].enable()
|
|
858
966
|
|
|
859
|
-
def __exit__(self, *exc):
|
|
967
|
+
def __exit__(self, *exc: Any) -> None:
|
|
860
968
|
self.simplug.hooks._registry = self.orig_registry
|
|
861
969
|
for name, status in self.orig_status.items():
|
|
862
970
|
self.simplug.hooks._registry[name].enabled = status
|
|
@@ -878,6 +986,11 @@ class Simplug:
|
|
|
878
986
|
|
|
879
987
|
PROJECTS: Dict[str, "Simplug"] = {}
|
|
880
988
|
|
|
989
|
+
_batch_index: int
|
|
990
|
+
hooks: SimplugHooks
|
|
991
|
+
project: str
|
|
992
|
+
_inited: bool
|
|
993
|
+
|
|
881
994
|
def __new__(cls, project: str) -> "Simplug":
|
|
882
995
|
if project not in cls.PROJECTS:
|
|
883
996
|
obj = super().__new__(cls)
|
|
@@ -886,7 +999,7 @@ class Simplug:
|
|
|
886
999
|
|
|
887
1000
|
return cls.PROJECTS[project]
|
|
888
1001
|
|
|
889
|
-
def __init__(self, project: str):
|
|
1002
|
+
def __init__(self, project: str) -> None:
|
|
890
1003
|
if getattr(self, "_inited", None):
|
|
891
1004
|
return
|
|
892
1005
|
self._batch_index = 0
|
|
@@ -896,8 +1009,8 @@ class Simplug:
|
|
|
896
1009
|
|
|
897
1010
|
def load_entrypoints(
|
|
898
1011
|
self,
|
|
899
|
-
group: str
|
|
900
|
-
only: str
|
|
1012
|
+
group: Optional[str] = None,
|
|
1013
|
+
only: Union[str, Iterable[str]] = (),
|
|
901
1014
|
) -> None:
|
|
902
1015
|
"""Load plugins from setuptools entry_points
|
|
903
1016
|
|
|
@@ -943,7 +1056,7 @@ class Simplug:
|
|
|
943
1056
|
# allow to use as a decorator
|
|
944
1057
|
return plugins[0]
|
|
945
1058
|
|
|
946
|
-
def get_plugin(self, name: str, raw: bool = False) ->
|
|
1059
|
+
def get_plugin(self, name: str, raw: bool = False) -> Union[SimplugWrapper, Any]:
|
|
947
1060
|
"""Get the plugin wrapper or the raw plugin object
|
|
948
1061
|
|
|
949
1062
|
Args:
|
|
@@ -963,7 +1076,7 @@ class Simplug:
|
|
|
963
1076
|
wrapper = self.hooks._registry[name]
|
|
964
1077
|
return wrapper.plugin if raw else wrapper
|
|
965
1078
|
|
|
966
|
-
def get_all_plugins(self, raw: bool = False) -> Dict[str,
|
|
1079
|
+
def get_all_plugins(self, raw: bool = False) -> Dict[str, Any]:
|
|
967
1080
|
"""Get a mapping of all plugins
|
|
968
1081
|
|
|
969
1082
|
Args:
|
|
@@ -981,7 +1094,7 @@ class Simplug:
|
|
|
981
1094
|
[(name, plugin.plugin) for name, plugin in self.hooks._registry.items()]
|
|
982
1095
|
)
|
|
983
1096
|
|
|
984
|
-
def get_enabled_plugins(self, raw: bool = False) -> Dict[str,
|
|
1097
|
+
def get_enabled_plugins(self, raw: bool = False) -> Dict[str, Any]:
|
|
985
1098
|
"""Get a mapping of all enabled plugins
|
|
986
1099
|
|
|
987
1100
|
Args:
|
|
@@ -1018,8 +1131,8 @@ class Simplug:
|
|
|
1018
1131
|
return [name for name, plugin in self.hooks._registry.items() if plugin.enabled]
|
|
1019
1132
|
|
|
1020
1133
|
def plugins_context(
|
|
1021
|
-
self, plugins: Iterable[Any]
|
|
1022
|
-
) -> SimplugContext
|
|
1134
|
+
self, plugins: Optional[Iterable[Any]]
|
|
1135
|
+
) -> Union[SimplugContext, nullcontext]:
|
|
1023
1136
|
"""A context manager with given plugins enabled or disabled
|
|
1024
1137
|
|
|
1025
1138
|
Args:
|
|
@@ -1080,11 +1193,11 @@ class Simplug:
|
|
|
1080
1193
|
|
|
1081
1194
|
def spec(
|
|
1082
1195
|
self,
|
|
1083
|
-
hook: Callable
|
|
1196
|
+
hook: Optional[Callable[..., Any]] = None,
|
|
1084
1197
|
required: bool = False,
|
|
1085
|
-
result: SimplugResult
|
|
1198
|
+
result: Union[SimplugResult, Callable] = SimplugResult.ALL_AVAILS,
|
|
1086
1199
|
warn_sync_impl_on_async: bool = True,
|
|
1087
|
-
) -> Callable:
|
|
1200
|
+
) -> Callable[..., Any]:
|
|
1088
1201
|
"""A decorator to define the specification of a hook
|
|
1089
1202
|
|
|
1090
1203
|
Args:
|
|
@@ -1133,7 +1246,7 @@ class Simplug:
|
|
|
1133
1246
|
|
|
1134
1247
|
return hook
|
|
1135
1248
|
|
|
1136
|
-
def impl(self, hook: Callable):
|
|
1249
|
+
def impl(self, hook: Callable[..., Any]) -> SimplugImpl:
|
|
1137
1250
|
"""A decorator for the implementation of a hook
|
|
1138
1251
|
|
|
1139
1252
|
Args:
|
|
File without changes
|
|
File without changes
|