simplug 0.5.2__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: simplug
3
- Version: 0.5.2
3
+ Version: 0.5.4
4
4
  Summary: A simple plugin system for python with async hooks supported
5
5
  License: MIT
6
6
  Author: pwwang
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "simplug"
3
- version = "0.5.2"
3
+ version = "0.5.4"
4
4
  description = "A simple plugin system for python with async hooks supported"
5
5
  authors = ["pwwang <pwwang@pwwang.com>"]
6
6
  license = "MIT"
@@ -8,7 +8,7 @@ install_requires = \
8
8
 
9
9
  setup_kwargs = {
10
10
  'name': 'simplug',
11
- 'version': '0.5.2',
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',
@@ -1,4 +1,5 @@
1
1
  """A simple entrypoint-free plugin system for python"""
2
+
2
3
  from __future__ import annotations
3
4
 
4
5
  import sys
@@ -8,20 +9,64 @@ from collections import namedtuple
8
9
  from contextlib import nullcontext
9
10
  from enum import Enum
10
11
  from importlib import import_module, metadata
11
- from typing import Any, Callable, Dict, Iterable, List, Tuple
12
+ from typing import Any, Callable, Dict, Iterable, List, Tuple, Union, Optional
12
13
 
13
14
  from diot import OrderedDiot
14
15
 
15
- __version__ = "0.5.2"
16
+ __version__ = "0.5.4"
16
17
 
17
- SimplugImpl = namedtuple("SimplugImpl", ["impl", "has_self"])
18
- SimplugImpl.__doc__ = """A namedtuple wrapper for hook implementation.
19
18
 
20
- This is used to mark the method/function to be an implementation of a hook.
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
21
69
 
22
- Args:
23
- impl: The hook implementation
24
- """
25
70
 
26
71
  SimplugImplCall = namedtuple(
27
72
  "SimplugImplCall",
@@ -92,19 +137,20 @@ class MultipleImplsForSingleResultHookWarning(Warning):
92
137
  class SimplugResult(Enum):
93
138
  """Way to get the results from the hooks
94
139
 
95
- ALL - Execute all implementations for the hook
96
- AVAIL(S) - Get non-`None` results
97
- FIRST - Get the first result, ordered by priority
98
- Don't excute the other the implementations
99
- LAST - Get the last result, ordered by priority
100
- Don't excute the other the implementations
101
- ALL_FIRST - Get the first result from each implementation and
102
- excute the other the implementations
103
- ALL_LAST - Get the last result from each implementation and
104
- excute the other the implementations
105
- TRY - Return `None` instead of raising `ResultUnavailableError` when
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
106
152
  no result is available
107
- SINGLE - Get the result from a single implementation
153
+ - SINGLE: Get the result from a single implementation
108
154
  """
109
155
 
110
156
  # 0b 1 1 1 1111
@@ -131,11 +177,12 @@ class SimplugResult(Enum):
131
177
  TRY_SINGLE = 0b100_1010 # 146
132
178
 
133
179
 
134
- def makecall(call: SimplugImplCall, async_hook: bool = False):
180
+ def makecall(call: SimplugImplCall, async_hook: bool = False) -> Any:
135
181
  """Make a call to an implementation and arguments
136
182
 
137
183
  Args:
138
184
  call: 3-element tuple of (implementation, args, kwargs)
185
+ async_hook: Whether this is being called from an async hook
139
186
 
140
187
  Returns:
141
188
  The result of the call
@@ -197,7 +244,12 @@ class SimplugWrapper:
197
244
  imported as a module
198
245
  """
199
246
 
200
- def __init__(self, plugin: Any, batch_index: int, index: int):
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:
201
253
  self.plugin = self._name = None
202
254
  if isinstance(plugin, str):
203
255
  try:
@@ -221,7 +273,7 @@ class SimplugWrapper:
221
273
  self.enabled = True # type: bool
222
274
 
223
275
  @property
224
- def version(self) -> str | None:
276
+ def version(self) -> Optional[str]:
225
277
  """Try to get the version of the plugin.
226
278
 
227
279
  If the attribute `version` is definied, use it. Otherwise, try to check
@@ -277,11 +329,11 @@ class SimplugWrapper:
277
329
  """Enable this plugin"""
278
330
  self.enabled = True
279
331
 
280
- def disable(self):
332
+ def disable(self) -> None:
281
333
  """Disable this plugin"""
282
334
  self.enabled = False
283
335
 
284
- def hook(self, name: str) -> SimplugImpl | None:
336
+ def hook(self, name: str) -> Optional[SimplugImpl]:
285
337
  """Get the hook implementation of this plugin by name
286
338
 
287
339
  Args:
@@ -321,35 +373,88 @@ class SimplugHook:
321
373
  spec: The specification of the hook
322
374
  required: Whether this hook is required to be implemented
323
375
  result: Way to collect the results from the hook
324
- _has_self: Whether the parameters have `self` as the first. If so,
325
- it will be ignored while being called.
376
+ debug: Whether to print debug messages
377
+ warn_sync_impl_on_async: Whether to warn about sync implementations
378
+ on async hooks
326
379
  """
327
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
+
328
389
  def __init__(
329
390
  self,
330
- simplug_hooks: SimplugHooks,
331
- spec: Callable,
391
+ simplug_hooks: "SimplugHooks",
392
+ spec: Callable[..., Any],
332
393
  required: bool,
333
- result: SimplugResult | Callable,
394
+ result: Union[SimplugResult, Callable],
334
395
  warn_sync_impl_on_async: bool = False,
335
- ):
396
+ ) -> None:
336
397
  self.simplug_hooks = simplug_hooks
337
398
  self.spec = spec
338
399
  self.name = spec.__name__
339
400
  self.required = required
340
401
  self.result = result
402
+ self.debug = False
341
403
  self.warn_sync_impl_on_async = warn_sync_impl_on_async
342
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
+
343
443
  def _get_results(
344
444
  self,
345
445
  calls: List[SimplugImplCall],
346
- plugin: str,
347
- result: SimplugResult | Callable | int = None,
446
+ plugin: Optional[str],
447
+ result: Optional[Union[SimplugResult, Callable, int]] = None,
348
448
  ) -> Any:
349
449
  """Get the results according to self.result"""
350
450
  result = self.result if result is None else result
351
451
 
352
452
  if callable(result):
453
+ if self.debug:
454
+ print(
455
+ "[simplug] - Gathering results using "
456
+ f"custom function {result.__name__}"
457
+ )
353
458
  return result(calls)
354
459
 
355
460
  if isinstance(result, SimplugResult):
@@ -366,44 +471,64 @@ class SimplugHook:
366
471
  if result & 0b010_0000:
367
472
  out = [makecall(call) for call in calls]
368
473
  if result == SimplugResult.ALL.value:
474
+ if self.debug:
475
+ print("[simplug] - Returning all results")
369
476
  return out
370
477
  if result == SimplugResult.ALL_AVAILS.value:
478
+ if self.debug:
479
+ print("[simplug] - Returning all available (non-None) results")
371
480
  return [x for x in out if x is not None]
372
481
  if result == SimplugResult.ALL_FIRST.value:
373
482
  if not out:
374
483
  raise ResultUnavailableError
484
+ if self.debug:
485
+ print("[simplug] - Returning first result")
375
486
  return out[0]
376
487
  if result == SimplugResult.ALL_LAST.value:
377
488
  if not out:
378
489
  raise ResultUnavailableError
490
+ if self.debug:
491
+ print("[simplug] - Returning last result")
379
492
  return out[-1]
380
493
  if result == SimplugResult.ALL_FIRST_AVAIL.value:
381
494
  if not out or all(x is None for x in out):
382
495
  raise ResultUnavailableError
496
+ if self.debug:
497
+ print("[simplug] - Returning first available (non-None) result")
383
498
  return next(x for x in out if x is not None)
384
499
  if result == SimplugResult.ALL_LAST_AVAIL.value:
385
500
  if not out or all(x is None for x in out):
386
501
  raise ResultUnavailableError
502
+ if self.debug:
503
+ print("[simplug] - Returning last available (non-None) result")
387
504
  return next(x for x in reversed(out) if x is not None)
388
505
 
389
506
  if result == SimplugResult.FIRST.value:
390
507
  if not calls:
391
508
  raise ResultUnavailableError
509
+ if self.debug:
510
+ print("[simplug] - Returning first result")
392
511
  return makecall(calls[0])
393
512
  if result == SimplugResult.LAST.value:
394
513
  if not calls:
395
514
  raise ResultUnavailableError
515
+ if self.debug:
516
+ print("[simplug] - Returning last result")
396
517
  return makecall(calls[-1])
397
518
  if result == SimplugResult.FIRST_AVAIL.value:
398
519
  for call in calls:
399
520
  ret = makecall(call)
400
521
  if ret is not None:
522
+ if self.debug:
523
+ print("[simplug] - Returning first available (non-None) result")
401
524
  return ret
402
525
  raise ResultUnavailableError
403
526
  if result == SimplugResult.LAST_AVAIL.value:
404
527
  for call in reversed(calls):
405
528
  ret = makecall(call)
406
529
  if ret is not None:
530
+ if self.debug:
531
+ print("[simplug] - Returning last available (non-None) result")
407
532
  return ret
408
533
  raise ResultUnavailableError
409
534
  if result == SimplugResult.SINGLE.value:
@@ -411,6 +536,10 @@ class SimplugHook:
411
536
  raise ResultUnavailableError
412
537
  for call in calls:
413
538
  if call.plugin == plugin:
539
+ if self.debug:
540
+ print(
541
+ f"[simplug] - Returning single result from plugin {plugin}"
542
+ )
414
543
  return makecall(call)
415
544
  if plugin is not None:
416
545
  raise ResultUnavailableError
@@ -420,9 +549,14 @@ class SimplugHook:
420
549
  "but a single result is expected. Using the last one.",
421
550
  MultipleImplsForSingleResultHookWarning,
422
551
  )
552
+ if self.debug:
553
+ print(
554
+ f"[simplug] - Returning single result from the last plugin "
555
+ f"{calls[-1].plugin}"
556
+ )
423
557
  return makecall(calls[-1])
424
558
 
425
- def __call__(self, *args, **kwargs):
559
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
426
560
  """Call the hook in your system
427
561
 
428
562
  Args:
@@ -449,6 +583,12 @@ class SimplugHook:
449
583
  "Cannot use __plugin with non-SimplugResult.(TRY_)SINGLE hooks"
450
584
  )
451
585
 
586
+ if self.debug:
587
+ print(
588
+ f"[simplug] Calling hook {self.name} with args={args}, kwargs={kwargs}, "
589
+ f"result={self.result}"
590
+ )
591
+
452
592
  _plugin = kwargs.pop("__plugin", None)
453
593
  calls = []
454
594
  for plugin in self.simplug_hooks._registry.values():
@@ -457,7 +597,10 @@ class SimplugHook:
457
597
  hook = plugin.hook(self.name)
458
598
 
459
599
  if hook is not None:
460
- plugin_args = (plugin.plugin, *args) if hook.has_self else args
600
+ plugin_args = self._prepare_plugin_args(plugin, hook, args)
601
+ if self.debug:
602
+ print(f"[simplug] - Pushing call {plugin.name}.{self.name}")
603
+
461
604
  calls.append(
462
605
  SimplugImplCall(plugin.name, hook.impl, plugin_args, kwargs)
463
606
  )
@@ -471,13 +614,18 @@ class SimplugHookAsync(SimplugHook):
471
614
  async def _get_results(
472
615
  self,
473
616
  calls: List[SimplugImplCall],
474
- plugin: str,
475
- result: SimplugResult | Callable | int = None,
617
+ plugin: Optional[str],
618
+ result: Optional[Union[SimplugResult, Callable, int]] = None,
476
619
  ) -> Any:
477
620
  """Get the results according to self.result"""
478
621
  result = self.result if result is None else result
479
622
 
480
623
  if callable(result):
624
+ if self.debug:
625
+ print(
626
+ "[simplug] - Gathering results using "
627
+ f"custom async function {result.__name__}"
628
+ )
481
629
  return await result(calls)
482
630
 
483
631
  if isinstance(result, SimplugResult):
@@ -498,44 +646,66 @@ class SimplugHookAsync(SimplugHook):
498
646
  if result & 0b010_0000:
499
647
  out = [await makecall(call, True) for call in calls]
500
648
  if result == SimplugResult.ALL.value:
649
+ if self.debug:
650
+ print("[simplug] - Returning all results")
501
651
  return out
502
652
  if result == SimplugResult.ALL_AVAILS.value:
653
+ if self.debug:
654
+ print("[simplug] - Returning all available (non-None) results")
503
655
  return [x for x in out if x is not None]
504
656
  if result == SimplugResult.ALL_FIRST.value:
505
657
  if not out:
506
658
  raise ResultUnavailableError
659
+ if self.debug:
660
+ print("[simplug] - Returning first result")
507
661
  return out[0]
508
662
  if result == SimplugResult.ALL_LAST.value:
509
663
  if not out:
510
664
  raise ResultUnavailableError
665
+ if self.debug:
666
+ print("[simplug] - Returning last result")
511
667
  return out[-1]
512
668
  if result == SimplugResult.ALL_FIRST_AVAIL.value:
513
669
  if not out or all(x is None for x in out):
514
670
  raise ResultUnavailableError
671
+ if self.debug:
672
+ print("[simplug] - Returning first available (non-None) result")
515
673
  return next(x for x in out if x is not None)
516
674
  if result == SimplugResult.ALL_LAST_AVAIL.value:
517
675
  if not out or all(x is None for x in out):
518
676
  raise ResultUnavailableError
677
+ if self.debug:
678
+ print("[simplug] - Returning last available (non-None) result")
519
679
  return next(x for x in reversed(out) if x is not None)
520
680
 
521
681
  if result == SimplugResult.FIRST.value:
522
682
  if not calls:
523
683
  raise ResultUnavailableError
684
+ if self.debug:
685
+ print("[simplug] - Returning first result")
524
686
  return await makecall(calls[0], True)
525
687
  if result == SimplugResult.LAST.value:
526
688
  if not calls:
527
689
  raise ResultUnavailableError
690
+ if self.debug:
691
+ print("[simplug] - Returning last result")
528
692
  return await makecall(calls[-1], True)
529
693
  if result == SimplugResult.FIRST_AVAIL.value:
530
694
  for call in calls:
531
695
  ret = await makecall(call, True)
532
696
  if ret is not None:
697
+ if self.debug:
698
+ print(
699
+ "[simplug] - Returning first available (non-None) result"
700
+ )
533
701
  return ret
534
702
  raise ResultUnavailableError
535
703
  if result == SimplugResult.LAST_AVAIL.value:
536
704
  for call in reversed(calls):
537
705
  ret = await makecall(call, True)
538
706
  if ret is not None:
707
+ if self.debug:
708
+ print("[simplug] - Returning last available (non-None) result")
539
709
  return ret
540
710
  raise ResultUnavailableError
541
711
  if result == SimplugResult.SINGLE.value:
@@ -543,6 +713,10 @@ class SimplugHookAsync(SimplugHook):
543
713
  raise ResultUnavailableError
544
714
  for call in calls:
545
715
  if call.plugin == plugin:
716
+ if self.debug:
717
+ print(
718
+ f"[simplug] - Returning single result from plugin {plugin}"
719
+ )
546
720
  return await makecall(call, True)
547
721
  if plugin is not None:
548
722
  raise ResultUnavailableError
@@ -552,9 +726,14 @@ class SimplugHookAsync(SimplugHook):
552
726
  "but no plugin was specified. Using the last one.",
553
727
  MultipleImplsForSingleResultHookWarning,
554
728
  )
729
+ if self.debug:
730
+ print(
731
+ f"[simplug] - Returning single result from the last plugin "
732
+ f"{calls[-1].plugin}"
733
+ )
555
734
  return await makecall(calls[-1], True)
556
735
 
557
- async def __call__(self, *args, **kwargs):
736
+ async def __call__(self, *args: Any, **kwargs: Any) -> Any:
558
737
  """Call the hook in your system asynchronously
559
738
 
560
739
  Args:
@@ -581,6 +760,12 @@ class SimplugHookAsync(SimplugHook):
581
760
  "Cannot use __plugin with non-SimplugResult.(TRY_)SINGLE hooks"
582
761
  )
583
762
 
763
+ if self.debug:
764
+ print(
765
+ f"[simplug] Calling async hook {self.name} with args={args}, "
766
+ f"kwargs={kwargs}, result={self.result}"
767
+ )
768
+
584
769
  _plugin = kwargs.pop("__plugin", None)
585
770
  calls = []
586
771
  for plugin in self.simplug_hooks._registry.values():
@@ -590,7 +775,9 @@ class SimplugHookAsync(SimplugHook):
590
775
  if hook is None: # pragma: no cover
591
776
  continue
592
777
 
593
- plugin_args = (plugin.plugin, *args) if hook.has_self else args
778
+ plugin_args = self._prepare_plugin_args(plugin, hook, args)
779
+ if self.debug:
780
+ print(f"[simplug] - Pushing call {plugin.name}.{self.name}")
594
781
  calls.append(SimplugImplCall(plugin.name, hook.impl, plugin_args, kwargs))
595
782
 
596
783
  return await self._get_results(calls, plugin=_plugin)
@@ -611,10 +798,14 @@ class SimplugHooks:
611
798
  _registry_sorted: Whether the plugin registry has been sorted already
612
799
  """
613
800
 
614
- def __init__(self):
801
+ _registry: OrderedDiot
802
+ _specs: Dict[str, Union["SimplugHook", "SimplugHookAsync"]]
803
+ _registry_sorted: bool
804
+
805
+ def __init__(self) -> None:
615
806
 
616
807
  self._registry = OrderedDiot()
617
- self._specs = {}
808
+ self._specs: Dict[str, Union[SimplugHook, SimplugHookAsync]] = {}
618
809
  self._registry_sorted = False
619
810
 
620
811
  def _register(self, plugin: SimplugWrapper) -> None:
@@ -691,7 +882,7 @@ class SimplugHooks:
691
882
  )
692
883
  self._registry_sorted = True
693
884
 
694
- def __getattr__(self, name: str) -> "SimplugHook":
885
+ def __getattr__(self, name: str) -> Union["SimplugHook", "SimplugHookAsync"]:
695
886
  """Get the hook by name
696
887
 
697
888
  Args:
@@ -712,7 +903,13 @@ class SimplugHooks:
712
903
  class SimplugContext:
713
904
  """The context manager for enabling or disabling a set of plugins"""
714
905
 
715
- def __init__(self, simplug: "Simplug", plugins: Iterable[Any]):
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:
716
913
  self.only = self._check_plugins(plugins)
717
914
  self.plugins = plugins
718
915
  self.simplug = simplug
@@ -736,12 +933,12 @@ class SimplugContext:
736
933
  )
737
934
  return False
738
935
 
739
- def _raise(self, exc: Exception):
936
+ def _raise(self, exc: Exception) -> None:
740
937
  """Raise the exception and restore the original status"""
741
938
  self.__exit__(*sys.exc_info())
742
939
  raise exc
743
940
 
744
- def __enter__(self):
941
+ def __enter__(self) -> None:
745
942
  if self.only:
746
943
  for plugin in self.orig_registry.values():
747
944
  plugin.disable()
@@ -767,7 +964,7 @@ class SimplugContext:
767
964
  self._raise(NoSuchPlugin(plugin))
768
965
  self.orig_registry[plugin].enable()
769
966
 
770
- def __exit__(self, *exc):
967
+ def __exit__(self, *exc: Any) -> None:
771
968
  self.simplug.hooks._registry = self.orig_registry
772
969
  for name, status in self.orig_status.items():
773
970
  self.simplug.hooks._registry[name].enabled = status
@@ -789,6 +986,11 @@ class Simplug:
789
986
 
790
987
  PROJECTS: Dict[str, "Simplug"] = {}
791
988
 
989
+ _batch_index: int
990
+ hooks: SimplugHooks
991
+ project: str
992
+ _inited: bool
993
+
792
994
  def __new__(cls, project: str) -> "Simplug":
793
995
  if project not in cls.PROJECTS:
794
996
  obj = super().__new__(cls)
@@ -797,7 +999,7 @@ class Simplug:
797
999
 
798
1000
  return cls.PROJECTS[project]
799
1001
 
800
- def __init__(self, project: str):
1002
+ def __init__(self, project: str) -> None:
801
1003
  if getattr(self, "_inited", None):
802
1004
  return
803
1005
  self._batch_index = 0
@@ -807,8 +1009,8 @@ class Simplug:
807
1009
 
808
1010
  def load_entrypoints(
809
1011
  self,
810
- group: str | None = None,
811
- only: str | Iterable[str] = (),
1012
+ group: Optional[str] = None,
1013
+ only: Union[str, Iterable[str]] = (),
812
1014
  ) -> None:
813
1015
  """Load plugins from setuptools entry_points
814
1016
 
@@ -854,7 +1056,7 @@ class Simplug:
854
1056
  # allow to use as a decorator
855
1057
  return plugins[0]
856
1058
 
857
- def get_plugin(self, name: str, raw: bool = False) -> object:
1059
+ def get_plugin(self, name: str, raw: bool = False) -> Union[SimplugWrapper, Any]:
858
1060
  """Get the plugin wrapper or the raw plugin object
859
1061
 
860
1062
  Args:
@@ -874,7 +1076,7 @@ class Simplug:
874
1076
  wrapper = self.hooks._registry[name]
875
1077
  return wrapper.plugin if raw else wrapper
876
1078
 
877
- def get_all_plugins(self, raw: bool = False) -> Dict[str, SimplugWrapper]:
1079
+ def get_all_plugins(self, raw: bool = False) -> Dict[str, Any]:
878
1080
  """Get a mapping of all plugins
879
1081
 
880
1082
  Args:
@@ -892,7 +1094,7 @@ class Simplug:
892
1094
  [(name, plugin.plugin) for name, plugin in self.hooks._registry.items()]
893
1095
  )
894
1096
 
895
- def get_enabled_plugins(self, raw: bool = False) -> Dict[str, SimplugWrapper]:
1097
+ def get_enabled_plugins(self, raw: bool = False) -> Dict[str, Any]:
896
1098
  """Get a mapping of all enabled plugins
897
1099
 
898
1100
  Args:
@@ -929,8 +1131,8 @@ class Simplug:
929
1131
  return [name for name, plugin in self.hooks._registry.items() if plugin.enabled]
930
1132
 
931
1133
  def plugins_context(
932
- self, plugins: Iterable[Any] | None
933
- ) -> SimplugContext | nullcontext:
1134
+ self, plugins: Optional[Iterable[Any]]
1135
+ ) -> Union[SimplugContext, nullcontext]:
934
1136
  """A context manager with given plugins enabled or disabled
935
1137
 
936
1138
  Args:
@@ -991,11 +1193,11 @@ class Simplug:
991
1193
 
992
1194
  def spec(
993
1195
  self,
994
- hook: Callable | None = None,
1196
+ hook: Optional[Callable[..., Any]] = None,
995
1197
  required: bool = False,
996
- result: SimplugResult | Callable = SimplugResult.ALL_AVAILS,
1198
+ result: Union[SimplugResult, Callable] = SimplugResult.ALL_AVAILS,
997
1199
  warn_sync_impl_on_async: bool = True,
998
- ) -> Callable:
1200
+ ) -> Callable[..., Any]:
999
1201
  """A decorator to define the specification of a hook
1000
1202
 
1001
1203
  Args:
@@ -1044,7 +1246,7 @@ class Simplug:
1044
1246
 
1045
1247
  return hook
1046
1248
 
1047
- def impl(self, hook: Callable):
1249
+ def impl(self, hook: Callable[..., Any]) -> SimplugImpl:
1048
1250
  """A decorator for the implementation of a hook
1049
1251
 
1050
1252
  Args:
File without changes
File without changes