simplug 0.5.2__tar.gz → 0.5.3__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.3
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.3"
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.3',
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
@@ -12,7 +13,7 @@ from typing import Any, Callable, Dict, Iterable, List, Tuple
12
13
 
13
14
  from diot import OrderedDiot
14
15
 
15
- __version__ = "0.5.2"
16
+ __version__ = "0.5.3"
16
17
 
17
18
  SimplugImpl = namedtuple("SimplugImpl", ["impl", "has_self"])
18
19
  SimplugImpl.__doc__ = """A namedtuple wrapper for hook implementation.
@@ -338,6 +339,7 @@ class SimplugHook:
338
339
  self.name = spec.__name__
339
340
  self.required = required
340
341
  self.result = result
342
+ self.debug = False
341
343
  self.warn_sync_impl_on_async = warn_sync_impl_on_async
342
344
 
343
345
  def _get_results(
@@ -350,6 +352,11 @@ class SimplugHook:
350
352
  result = self.result if result is None else result
351
353
 
352
354
  if callable(result):
355
+ if self.debug:
356
+ print(
357
+ "[simplug] - Gathering results using "
358
+ f"custom function {result.__name__}"
359
+ )
353
360
  return result(calls)
354
361
 
355
362
  if isinstance(result, SimplugResult):
@@ -366,44 +373,64 @@ class SimplugHook:
366
373
  if result & 0b010_0000:
367
374
  out = [makecall(call) for call in calls]
368
375
  if result == SimplugResult.ALL.value:
376
+ if self.debug:
377
+ print("[simplug] - Returning all results")
369
378
  return out
370
379
  if result == SimplugResult.ALL_AVAILS.value:
380
+ if self.debug:
381
+ print("[simplug] - Returning all available (non-None) results")
371
382
  return [x for x in out if x is not None]
372
383
  if result == SimplugResult.ALL_FIRST.value:
373
384
  if not out:
374
385
  raise ResultUnavailableError
386
+ if self.debug:
387
+ print("[simplug] - Returning first result")
375
388
  return out[0]
376
389
  if result == SimplugResult.ALL_LAST.value:
377
390
  if not out:
378
391
  raise ResultUnavailableError
392
+ if self.debug:
393
+ print("[simplug] - Returning last result")
379
394
  return out[-1]
380
395
  if result == SimplugResult.ALL_FIRST_AVAIL.value:
381
396
  if not out or all(x is None for x in out):
382
397
  raise ResultUnavailableError
398
+ if self.debug:
399
+ print("[simplug] - Returning first available (non-None) result")
383
400
  return next(x for x in out if x is not None)
384
401
  if result == SimplugResult.ALL_LAST_AVAIL.value:
385
402
  if not out or all(x is None for x in out):
386
403
  raise ResultUnavailableError
404
+ if self.debug:
405
+ print("[simplug] - Returning last available (non-None) result")
387
406
  return next(x for x in reversed(out) if x is not None)
388
407
 
389
408
  if result == SimplugResult.FIRST.value:
390
409
  if not calls:
391
410
  raise ResultUnavailableError
411
+ if self.debug:
412
+ print("[simplug] - Returning first result")
392
413
  return makecall(calls[0])
393
414
  if result == SimplugResult.LAST.value:
394
415
  if not calls:
395
416
  raise ResultUnavailableError
417
+ if self.debug:
418
+ print("[simplug] - Returning last result")
396
419
  return makecall(calls[-1])
397
420
  if result == SimplugResult.FIRST_AVAIL.value:
398
421
  for call in calls:
399
422
  ret = makecall(call)
400
423
  if ret is not None:
424
+ if self.debug:
425
+ print("[simplug] - Returning first available (non-None) result")
401
426
  return ret
402
427
  raise ResultUnavailableError
403
428
  if result == SimplugResult.LAST_AVAIL.value:
404
429
  for call in reversed(calls):
405
430
  ret = makecall(call)
406
431
  if ret is not None:
432
+ if self.debug:
433
+ print("[simplug] - Returning last available (non-None) result")
407
434
  return ret
408
435
  raise ResultUnavailableError
409
436
  if result == SimplugResult.SINGLE.value:
@@ -411,6 +438,10 @@ class SimplugHook:
411
438
  raise ResultUnavailableError
412
439
  for call in calls:
413
440
  if call.plugin == plugin:
441
+ if self.debug:
442
+ print(
443
+ f"[simplug] - Returning single result from plugin {plugin}"
444
+ )
414
445
  return makecall(call)
415
446
  if plugin is not None:
416
447
  raise ResultUnavailableError
@@ -420,6 +451,11 @@ class SimplugHook:
420
451
  "but a single result is expected. Using the last one.",
421
452
  MultipleImplsForSingleResultHookWarning,
422
453
  )
454
+ if self.debug:
455
+ print(
456
+ f"[simplug] - Returning single result from the last plugin "
457
+ f"{calls[-1].plugin}"
458
+ )
423
459
  return makecall(calls[-1])
424
460
 
425
461
  def __call__(self, *args, **kwargs):
@@ -449,6 +485,12 @@ class SimplugHook:
449
485
  "Cannot use __plugin with non-SimplugResult.(TRY_)SINGLE hooks"
450
486
  )
451
487
 
488
+ if self.debug:
489
+ print(
490
+ f"[simplug] Calling hook {self.name} with args={args}, kwargs={kwargs}, "
491
+ f"result={self.result}"
492
+ )
493
+
452
494
  _plugin = kwargs.pop("__plugin", None)
453
495
  calls = []
454
496
  for plugin in self.simplug_hooks._registry.values():
@@ -458,6 +500,9 @@ class SimplugHook:
458
500
 
459
501
  if hook is not None:
460
502
  plugin_args = (plugin.plugin, *args) if hook.has_self else args
503
+ if self.debug:
504
+ print(f"[simplug] - Pushing call {plugin.name}.{self.name}")
505
+
461
506
  calls.append(
462
507
  SimplugImplCall(plugin.name, hook.impl, plugin_args, kwargs)
463
508
  )
@@ -478,6 +523,11 @@ class SimplugHookAsync(SimplugHook):
478
523
  result = self.result if result is None else result
479
524
 
480
525
  if callable(result):
526
+ if self.debug:
527
+ print(
528
+ "[simplug] - Gathering results using "
529
+ f"custom async function {result.__name__}"
530
+ )
481
531
  return await result(calls)
482
532
 
483
533
  if isinstance(result, SimplugResult):
@@ -498,44 +548,66 @@ class SimplugHookAsync(SimplugHook):
498
548
  if result & 0b010_0000:
499
549
  out = [await makecall(call, True) for call in calls]
500
550
  if result == SimplugResult.ALL.value:
551
+ if self.debug:
552
+ print("[simplug] - Returning all results")
501
553
  return out
502
554
  if result == SimplugResult.ALL_AVAILS.value:
555
+ if self.debug:
556
+ print("[simplug] - Returning all available (non-None) results")
503
557
  return [x for x in out if x is not None]
504
558
  if result == SimplugResult.ALL_FIRST.value:
505
559
  if not out:
506
560
  raise ResultUnavailableError
561
+ if self.debug:
562
+ print("[simplug] - Returning first result")
507
563
  return out[0]
508
564
  if result == SimplugResult.ALL_LAST.value:
509
565
  if not out:
510
566
  raise ResultUnavailableError
567
+ if self.debug:
568
+ print("[simplug] - Returning last result")
511
569
  return out[-1]
512
570
  if result == SimplugResult.ALL_FIRST_AVAIL.value:
513
571
  if not out or all(x is None for x in out):
514
572
  raise ResultUnavailableError
573
+ if self.debug:
574
+ print("[simplug] - Returning first available (non-None) result")
515
575
  return next(x for x in out if x is not None)
516
576
  if result == SimplugResult.ALL_LAST_AVAIL.value:
517
577
  if not out or all(x is None for x in out):
518
578
  raise ResultUnavailableError
579
+ if self.debug:
580
+ print("[simplug] - Returning last available (non-None) result")
519
581
  return next(x for x in reversed(out) if x is not None)
520
582
 
521
583
  if result == SimplugResult.FIRST.value:
522
584
  if not calls:
523
585
  raise ResultUnavailableError
586
+ if self.debug:
587
+ print("[simplug] - Returning first result")
524
588
  return await makecall(calls[0], True)
525
589
  if result == SimplugResult.LAST.value:
526
590
  if not calls:
527
591
  raise ResultUnavailableError
592
+ if self.debug:
593
+ print("[simplug] - Returning last result")
528
594
  return await makecall(calls[-1], True)
529
595
  if result == SimplugResult.FIRST_AVAIL.value:
530
596
  for call in calls:
531
597
  ret = await makecall(call, True)
532
598
  if ret is not None:
599
+ if self.debug:
600
+ print(
601
+ "[simplug] - Returning first available (non-None) result"
602
+ )
533
603
  return ret
534
604
  raise ResultUnavailableError
535
605
  if result == SimplugResult.LAST_AVAIL.value:
536
606
  for call in reversed(calls):
537
607
  ret = await makecall(call, True)
538
608
  if ret is not None:
609
+ if self.debug:
610
+ print("[simplug] - Returning last available (non-None) result")
539
611
  return ret
540
612
  raise ResultUnavailableError
541
613
  if result == SimplugResult.SINGLE.value:
@@ -543,6 +615,10 @@ class SimplugHookAsync(SimplugHook):
543
615
  raise ResultUnavailableError
544
616
  for call in calls:
545
617
  if call.plugin == plugin:
618
+ if self.debug:
619
+ print(
620
+ f"[simplug] - Returning single result from plugin {plugin}"
621
+ )
546
622
  return await makecall(call, True)
547
623
  if plugin is not None:
548
624
  raise ResultUnavailableError
@@ -552,6 +628,11 @@ class SimplugHookAsync(SimplugHook):
552
628
  "but no plugin was specified. Using the last one.",
553
629
  MultipleImplsForSingleResultHookWarning,
554
630
  )
631
+ if self.debug:
632
+ print(
633
+ f"[simplug] - Returning single result from the last plugin "
634
+ f"{calls[-1].plugin}"
635
+ )
555
636
  return await makecall(calls[-1], True)
556
637
 
557
638
  async def __call__(self, *args, **kwargs):
@@ -581,6 +662,12 @@ class SimplugHookAsync(SimplugHook):
581
662
  "Cannot use __plugin with non-SimplugResult.(TRY_)SINGLE hooks"
582
663
  )
583
664
 
665
+ if self.debug:
666
+ print(
667
+ f"[simplug] Calling async hook {self.name} with args={args}, "
668
+ f"kwargs={kwargs}, result={self.result}"
669
+ )
670
+
584
671
  _plugin = kwargs.pop("__plugin", None)
585
672
  calls = []
586
673
  for plugin in self.simplug_hooks._registry.values():
@@ -591,6 +678,8 @@ class SimplugHookAsync(SimplugHook):
591
678
  continue
592
679
 
593
680
  plugin_args = (plugin.plugin, *args) if hook.has_self else args
681
+ if self.debug:
682
+ print(f"[simplug] - Pushing call {plugin.name}.{self.name}")
594
683
  calls.append(SimplugImplCall(plugin.name, hook.impl, plugin_args, kwargs))
595
684
 
596
685
  return await self._get_results(calls, plugin=_plugin)
File without changes
File without changes