PKNpyplugs/__init__.py"""PyPlugs, decorator based plug-in architecture for Python See {url} for more information. Current maintainers: -------------------- {maintainers} """ # Standard library imports from datetime import date as _date from collections import namedtuple as _namedtuple # Include PyPlugs functions at top level from pyplugs._plugins import * # noqa from pyplugs._exceptions import * # noqa # Version of PyPlugs. # # This is automatically set using the bumpversion tool __version__ = "0.2.2" # Homepage for PyPlugs __url__ = "https://pyplugs.readthedocs.io/" # Authors/maintainers of Pyplugs _Author = _namedtuple("_Author", ["name", "email", "start", "end"]) _AUTHORS = [ _Author("Geir Arne Hjelle", "geirarne@gmail.com", _date(2019, 4, 1), _date.max) ] __author__ = ", ".join(a.name for a in _AUTHORS if a.start < _date.today() < a.end) __contact__ = ", ".join(a.email for a in _AUTHORS if a.start < _date.today() < a.end) # Update doc with info about maintainers def _update_doc(doc: str) -> str: """Add information to doc-string Args: doc: The doc-string to update. Returns: The updated doc-string. """ # Maintainers maintainer_list = [ f"+ {a.name} <{a.email}>" for a in _AUTHORS if a.start < _date.today() < a.end ] maintainers = "\n".join(maintainer_list) # Add to doc-string return doc.format(maintainers=maintainers, url=__url__) __doc__ = _update_doc(__doc__) PK2Npyplugs/_exceptions.py"""Exceptions for the Pyplugs package Custom exceptions used by Pyplugs for more helpful error messages """ class PyplugsException(Exception): """Base class for all Pyplugs exceptions""" class UnknownPackageError(PyplugsException): """Pyplugs could not import the given package""" class UnknownPluginError(PyplugsException): """Pyplugs could not locate the given plugin""" class UnknownPluginFunctionError(PyplugsException): """Pyplugs could not locate the given function within a plugin""" PK3N2G pyplugs/_plugins.py"""Decorators for registering plugins """ # Standard library imports import functools import importlib import sys import textwrap from typing import Any, Callable, Dict, List, Optional from typing import NamedTuple from typing import overload, TypeVar # Use backport of importlib.resources if necessary try: from importlib import resources except ImportError: # pragma: nocover import importlib_resources as resources # type: ignore # Pyplugs imports from pyplugs import _exceptions # Type aliases T = TypeVar("T") Plugin = Callable[..., Any] # Only expose decorated functions to the outside __all__ = [] def expose(func: Callable[..., T]) -> Callable[..., T]: """Add function to __all__ so it will be exposed at the top level""" __all__.append(func.__name__) return func class PluginInfo(NamedTuple): """Information about one plug-in""" package_name: str plugin_name: str func_name: str func: Plugin description: str doc: str module_doc: str sort_value: float # Dictionary with information about all registered plug-ins _PLUGINS: Dict[str, Dict[str, Dict[str, PluginInfo]]] = dict() @overload def register(func: None, *, sort_value: int) -> Callable[[Plugin], Plugin]: """Signature for using decorator with parameters""" ... # pragma: nocover @overload def register(func: Plugin) -> Plugin: """Signature for using decorator without parameters""" ... # pragma: nocover @expose def register( _func: Optional[Plugin] = None, *, sort_value: float = 0 ) -> Callable[..., Any]: """Decorator for registering a new plug-in""" def decorator_register(func: Callable[..., T]) -> Callable[..., T]: package_name, _, plugin_name = func.__module__.rpartition(".") description, _, doc = (func.__doc__ or "").partition("\n\n") func_name = func.__name__ module_doc = sys.modules[func.__module__].__doc__ or "" pkg_info = _PLUGINS.setdefault(package_name, dict()) plugin_info = pkg_info.setdefault(plugin_name, dict()) plugin_info[func_name] = PluginInfo( package_name=package_name, plugin_name=plugin_name, func_name=func_name, func=func, description=description, doc=textwrap.dedent(doc).strip(), module_doc=module_doc, sort_value=sort_value, ) return func if _func is None: return decorator_register else: return decorator_register(_func) @expose def names(package: str) -> List[str]: """List all plug-ins in one package""" _import_all(package) return sorted(_PLUGINS[package].keys(), key=lambda p: info(package, p).sort_value) @expose def funcs(package: str, plugin: str) -> List[str]: """List all functions in one plug-in""" _import(package, plugin) plugin_info = _PLUGINS[package][plugin] return list(plugin_info.keys()) @expose def info(package: str, plugin: str, func: Optional[str] = None) -> PluginInfo: """Get information about a plug-in""" _import(package, plugin) try: plugin_info = _PLUGINS[package][plugin] except KeyError: raise _exceptions.UnknownPluginError( f"Could not find any plug-in named {plugin!r} inside {package!r}. " "Use pyplugs.register to register functions as plug-ins" ) func = next(iter(plugin_info.keys())) if func is None else func try: return plugin_info[func] except KeyError: raise _exceptions.UnknownPluginFunctionError( f"Could not find any function named {func!r} inside '{package}.{plugin}'. " "Use pyplugs.register to register plug-in functions" ) @expose def get(package: str, plugin: str, func: Optional[str] = None) -> Plugin: """Get a given plugin""" return info(package, plugin, func).func @expose def call( package: str, plugin: str, func: Optional[str] = None, *args: Any, **kwargs: Any ) -> Any: """Call the given plugin""" plugin_func = get(package, plugin, func) return plugin_func(*args, **kwargs) def _import(package: str, plugin: str) -> None: """Import the given plugin file from a package""" plugin_module = f"{package}.{plugin}" try: importlib.import_module(plugin_module) except ImportError as err: raise _exceptions.UnknownPluginError(err) from None def _import_all(package: str) -> None: """Import all plugins in a package""" try: all_resources = resources.contents(package) # type: ignore except ImportError as err: raise _exceptions.UnknownPackageError(err) from None # Note that we have tried to import the package by adding it to _PLUGINS _PLUGINS.setdefault(package, dict()) # Loop through all Python files in the directories of the package plugins = [ r[:-3] for r in all_resources if r.endswith(".py") and not r.startswith("_") ] for plugin in plugins: _import(package, plugin) @expose def names_factory(package: str) -> Callable[[], List[str]]: """Create a names() function for one package""" return functools.partial(names, package) @expose def funcs_factory(package: str) -> Callable[[str], List[str]]: """Create a funcs() function for one package""" return functools.partial(funcs, package) @expose def info_factory(package: str) -> Callable[[str, Optional[str]], PluginInfo]: """Create a info() function for one package""" return functools.partial(info, package) @expose def get_factory(package: str) -> Callable[[str, Optional[str]], Plugin]: """Create a get() function for one package""" return functools.partial(get, package) @expose def call_factory(package: str) -> Callable[..., Any]: """Create a call() function for one package""" return functools.partial(call, package) PK|N$011pyplugs-0.2.2.dist-info/LICENSEMIT License Copyright (c) 2019 Geir Arne Hjelle Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!HPOpyplugs-0.2.2.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UrPK!H l pyplugs-0.2.2.dist-info/METADATAVmo6_qk7t")̀nPmA6Fb^ M%֔E}Xu;'=LJB3x+uq]SZܲM(>̗%7m v⇐І;m`-f"Y7aAi ] ]bT8 j&I.]e=*)V^yb&iDDI JB芭\r s@~4h^d `hDgrX趭IP'^ULqkB"cJ%aaRj,D05#$ͨq>X unF@&pZF7JW!gc[HTV&fp6#6cm{`A`X7Eu3Z,ۜg9&uQuXܝ&=cbI^>rVU"E'lJH}ǿB cp_]lDt+B7Msلvs0$T`JZ?q\!pɗN kW xۑ:e ~ *:\wv,ٯ.!16r⭅p)3p?P.sӼx-kr]Amp0`A+[ꑒvN!_A DVeX[mɼ,֬8]N(hhO`:2zJG˴*O2̤놣$~U-iǖPK!H! {X pyplugs-0.2.2.dist-info/RECORDuλr@gYR@JiF\d1')$sc[ Y â.H.yBd&ۦՠcHy2+դm&y1CvV$-)9n_{GZbmf\bPMFO1dzA JޥL5m]˪fuRF"E/EONxueF$UD>vJS#ŝ}Cbl̪kc}F /PKNpyplugs/__init__.pyPK2Npyplugs/_exceptions.pyPK3N2G pyplugs/_plugins.pyPK|N$011Bpyplugs-0.2.2.dist-info/LICENSEPK!HPO#pyplugs-0.2.2.dist-info/WHEELPK!H l ;$pyplugs-0.2.2.dist-info/METADATAPK!H! {X ](pyplugs-0.2.2.dist-info/RECORDPK)