From 96301727a0e9f26e18777df52356281a700644c9 Mon Sep 17 00:00:00 2001 From: pwwang Date: Thu, 12 May 2022 14:12:26 -0700 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=8C=20Clean=20up=20and=20pin=20deps?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build.yml | 12 +- .github/workflows/docs.yml | 4 +- .pre-commit-config.yaml | 41 +-- .pylintrc | 614 ------------------------------------ README.rst | 195 ------------ poetry.lock | 311 ++++++++++++++++++ pyproject.toml | 7 +- requirements.txt | 3 - simplug.py | 205 +++++++----- 9 files changed, 465 insertions(+), 927 deletions(-) delete mode 100644 .pylintrc delete mode 100644 README.rst create mode 100644 poetry.lock delete mode 100644 requirements.txt diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ea069ca..4de2e43 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -9,7 +9,7 @@ jobs: if: "! contains(github.event.head_commit.message, 'wip')" strategy: matrix: - python-version: [3.7, 3.8] + python-version: [3.7, 3.8, 3.9, "3.10"] steps: - uses: actions/checkout@v2 @@ -22,10 +22,10 @@ jobs: python -m pip install --upgrade pip python -m pip install poetry poetry config virtualenvs.create false - python -m pip install pylint + python -m pip install flake8 poetry install -v - - name: Run pylint - run: pylint simplug + - name: Run flake8 + run: flake8 simplug.py - name: Test with pytest run: poetry run pytest tests/ --junitxml=junit/test-results-${{ matrix.python-version }}.xml - name: Upload pytest test results @@ -37,7 +37,7 @@ jobs: if: ${{ always() }} - name: Run codacy-coverage-reporter uses: codacy/codacy-coverage-reporter-action@master - if: matrix.python-version == 3.8 + if: matrix.python-version == 3.9 with: project-token: ${{ secrets.CODACY_PROJECT_TOKEN }} coverage-reports: .coverage.xml @@ -48,7 +48,7 @@ jobs: if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags') strategy: matrix: - python-version: [3.8] + python-version: [3.9] steps: - uses: actions/checkout@v2 - name: Setup Python # Set Python version diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index e40aefc..73bbb80 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -8,7 +8,7 @@ jobs: if: "! contains(github.event.head_commit.message, 'wip')" strategy: matrix: - python-version: [3.8] + python-version: [3.9] steps: - uses: actions/checkout@v2 - name: Setup Python # Set Python version @@ -37,7 +37,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: [3.8] + python-version: [3.9] steps: - uses: actions/checkout@v2 with: diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d001254..da221e0 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,7 +1,7 @@ # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks fail_fast: false -exclude: '^README.rst$|^tests/|^setup.py$|^examples/' +exclude: '^tests/|^setup\.py$|^examples/' repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: 5df1a4bf6f04a1ed3a643167b38d502575e29aef @@ -12,39 +12,28 @@ repos: - id: check-added-large-files - repo: local hooks: - - id: masterpylintrc - name: Overwrite local .pylintrc by master one - entry: cp ../.pylintrc ./.pylintrc - files: ../.pylintrc - pass_filenames: false - always_run: true - language: system -- repo: https://github.com/pre-commit/mirrors-pylint - rev: v2.4.4 - hooks: - - id: pylint + - id: flake8 + name: Run flake8 files: ^simplug\.py$ - pass_filenames: false + pass_filenames: true + entry: flake8 types: [python] - args: [simplug.py] -- repo: local - hooks: - - id: poetry2setuppy - name: Convert pyproject.toml to setup.py - entry: dephell deps convert --from=poetry --to=setup.py language: system - files: pyproject.toml - pass_filenames: false - - id: poetry2requirements - name: Convert pyproject.toml to requirements.txt - entry: dephell deps convert --from=poetry --to=requirements.txt + - id: versionchecker + name: Check version agreement in pyproject and __version__ + entry: bash -c language: system - files: pyproject.toml + args: + - get_ver() { echo $(egrep "^__version|^version" $1 | cut -d= -f2 | sed 's/\"\| //g'); }; + v1=`get_ver pyproject.toml`; + v2=`get_ver simplug.py`; + if [[ $v1 == $v2 ]]; then exit 0; else exit 1; fi pass_filenames: false + files: ^pyproject\.toml|simplug\.py$ - id: pytest name: Run pytest entry: pytest language: system args: [tests/] pass_filenames: false - files: ^tests/.+$|simplug\.py$ + files: ^tests/.+$|^simplug\.py$ diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index 21c923f..0000000 --- a/.pylintrc +++ /dev/null @@ -1,614 +0,0 @@ -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code. -extension-pkg-whitelist= - -# Add files or directories to the blacklist. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the blacklist. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the -# number of processors available to use. -jobs=1 - -# Control the amount of potential inferred values when inferring a single -# object. This can help the performance when dealing with large functions or -# complex, nested conditions. -limit-inference-results=100 - -# List of plugins (as comma separated values of python module names) to load, -# usually to register additional checkers. -load-plugins= - -# Pickle collected data for later comparisons. -persistent=yes - -# Specify a configuration file. -#rcfile= - -# When enabled, pylint would attempt to guess common misconfiguration and emit -# user-friendly hints instead of false-positive error messages. -suggestion-mode=yes - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once). You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use "--disable=all --enable=classes -# --disable=W". -disable=print-statement, - parameter-unpacking, - unpacking-in-except, - old-raise-syntax, - backtick, - long-suffix, - old-ne-operator, - old-octal-literal, - import-star-module-level, - non-ascii-bytes-literal, - raw-checker-failed, - bad-inline-option, - locally-disabled, - file-ignored, - suppressed-message, - useless-suppression, - deprecated-pragma, - use-symbolic-message-instead, - apply-builtin, - basestring-builtin, - buffer-builtin, - cmp-builtin, - coerce-builtin, - execfile-builtin, - file-builtin, - long-builtin, - raw_input-builtin, - reduce-builtin, - standarderror-builtin, - unicode-builtin, - xrange-builtin, - coerce-method, - delslice-method, - getslice-method, - setslice-method, - no-absolute-import, - old-division, - dict-iter-method, - dict-view-method, - next-method-called, - metaclass-assignment, - indexing-exception, - raising-string, - reload-builtin, - oct-method, - hex-method, - nonzero-method, - cmp-method, - input-builtin, - round-builtin, - intern-builtin, - unichr-builtin, - map-builtin-not-iterating, - zip-builtin-not-iterating, - range-builtin-not-iterating, - filter-builtin-not-iterating, - using-cmp-argument, - eq-without-hash, - div-method, - idiv-method, - rdiv-method, - exception-message-attribute, - invalid-str-codec, - sys-max-int, - bad-python3-import, - deprecated-string-function, - deprecated-str-translate-call, - deprecated-itertools-function, - deprecated-types-field, - next-method-defined, - dict-items-not-iterating, - dict-keys-not-iterating, - dict-values-not-iterating, - deprecated-operator-function, - deprecated-urllib-function, - xreadlines-attribute, - deprecated-sys-function, - exception-escape, - comprehension-escape, - import-error, - protected-access, - import-outside-toplevel, - no-name-in-module, - no-member, - broad-except, - cyclic-import, - too-few-public-methods, - unbalanced-tuple-unpacking, - no-self-use, - too-few-public-methods, - protected-access, - too-many-instance-attributes, - too-many-arguments, - too-many-return-statements, - too-many-locals - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable=c-extension-no-member - - -[REPORTS] - -# Python expression which should return a score less than or equal to 10. You -# have access to the variables 'error', 'warning', 'refactor', and 'convention' -# which contain the number of messages in each category, as well as 'statement' -# which is the total number of statements analyzed. This score is used by the -# global evaluation report (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details. -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio). You can also give a reporter class, e.g. -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Tells whether to display a full report or only the messages. -reports=no - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - -# Complete name of functions that never returns. When checking for -# inconsistent-return-statements if a never returning function is called then -# it will be considered as an explicit return statement and no message will be -# printed. -never-returning-functions=sys.exit - - -[LOGGING] - -# Format style used to check logging format string. `old` means using % -# formatting, `new` is for `{}` formatting,and `fstr` is for f-strings. -logging-format-style=old - -# Logging modules to check that the string format arguments are in logging -# function parameter format. -logging-modules=logging - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=yes - -# Minimum lines number of a similarity. -min-similarity-lines=4 - - -[SPELLING] - -# Limits count of emitted suggestions for spelling mistakes. -max-spelling-suggestions=4 - -# Spelling dictionary name. Available dictionaries: none. To make it work, -# install the python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains the private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to the private dictionary (see the -# --spelling-private-dict-file option) instead of raising a message. -spelling-store-unknown-words=no - - -[BASIC] - -# Naming style matching correct argument names. -argument-naming-style=snake_case - -# Regular expression matching correct argument names. Overrides argument- -# naming-style. -#argument-rgx= - -# Naming style matching correct attribute names. -attr-naming-style=snake_case - -# Regular expression matching correct attribute names. Overrides attr-naming- -# style. -#attr-rgx= - -# Bad variable names which should always be refused, separated by a comma. -bad-names=foo, - bar, - baz, - toto, - tutu, - tata - -# Naming style matching correct class attribute names. -class-attribute-naming-style=any - -# Regular expression matching correct class attribute names. Overrides class- -# attribute-naming-style. -#class-attribute-rgx= - -# Naming style matching correct class names. -class-naming-style=PascalCase - -# Regular expression matching correct class names. Overrides class-naming- -# style. -#class-rgx= - -# Naming style matching correct constant names. -const-naming-style=UPPER_CASE - -# Regular expression matching correct constant names. Overrides const-naming- -# style. -#const-rgx= - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - -# Naming style matching correct function names. -function-naming-style=snake_case - -# Regular expression matching correct function names. Overrides function- -# naming-style. -#function-rgx= - -# Good variable names which should always be accepted, separated by a comma. -good-names=i, - j, - k, - x, - y, - z, - np, - gc, - nn, - ns, - t, - t0, - to, - ex, - rc, - eq, - do, - by, - tf, - on, - op, - Run, - _ - -# Include a hint for the correct naming format with invalid-name. -include-naming-hint=no - -# Naming style matching correct inline iteration names. -inlinevar-naming-style=any - -# Regular expression matching correct inline iteration names. Overrides -# inlinevar-naming-style. -#inlinevar-rgx= - -# Naming style matching correct method names. -method-naming-style=snake_case - -# Regular expression matching correct method names. Overrides method-naming- -# style. -#method-rgx= - -# Naming style matching correct module names. -module-naming-style=snake_case - -# Regular expression matching correct module names. Overrides module-naming- -# style. -#module-rgx= - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -# These decorators are taken in consideration only for invalid-name. -property-classes=abc.abstractproperty - -# Naming style matching correct variable names. -variable-naming-style=snake_case - -# Regular expression matching correct variable names. Overrides variable- -# naming-style. -#variable-rgx= - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# Tells whether to warn about missing members when the owner of the attribute -# is inferred to be None. -ignore-none=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis). It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules= - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - -# List of decorators that change the signature of a decorated function. -signature-mutators= - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -notes=FIXME, - XXX, - TODO - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -expected-line-ending-format= - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=80 - -# Maximum number of lines in a module. -max-module-lines=1000 - -# List of optional constructs for which whitespace checking is disabled. `dict- -# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. -# `trailing-comma` allows a space between comma and closing bracket: (a, ). -# `empty-line` allows space-only lines. -no-space-check=trailing-comma, - dict-separator - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[STRING] - -# This flag controls whether the implicit-str-concat-in-sequence should -# generate a warning on implicit string concatenation in sequences defined over -# several lines. -check-str-concat-over-line-jumps=no - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid defining new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_, - _cb - -# A regular expression matching the name of dummy variables (i.e. expected to -# not be used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore. -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io - - -[DESIGN] - -# Maximum number of arguments for function / method. -max-args=5 - -# Maximum number of attributes for a class (see R0902). -max-attributes=7 - -# Maximum number of boolean expressions in an if statement (see R0916). -max-bool-expr=5 - -# Maximum number of branch for function / method body. -max-branches=15 - -# Maximum number of locals for function / method body. -max-locals=15 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body. -max-returns=6 - -# Maximum number of statements in function / method body. -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=2 - - -[IMPORTS] - -# List of modules that can be imported at any level, not just the top level -# one. -allow-any-import-level= - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=no - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - -# Deprecated modules which should not be used, separated by a comma. -deprecated-modules=optparse,tkinter.tix - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled). -ext-import-graph= - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled). -import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled). -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - -# Couples of modules and preferred modules, separated by a comma. -preferred-modules= - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__, - __new__, - setUp, - __post_init__ - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict, - _fields, - _replace, - _source, - _make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=cls - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "BaseException, Exception". -overgeneral-exceptions=BaseException, - Exception diff --git a/README.rst b/README.rst deleted file mode 100644 index fd570f7..0000000 --- a/README.rst +++ /dev/null @@ -1,195 +0,0 @@ - -simplug -======= - -A simple plugin system for python with async hooks supported - -Installation ------------- - -.. code-block:: - - pip install -U simplug - -Examples --------- - -A toy example -^^^^^^^^^^^^^ - -.. code-block:: python - - from simplug import Simplug - - simplug = Simplug('project') - - class MySpec: - """A hook specification namespace.""" - - @simplug.spec - def myhook(self, arg1, arg2): - """My special little hook that you can customize.""" - - class Plugin_1: - """A hook implementation namespace.""" - - @simplug.impl - def myhook(self, arg1, arg2): - print("inside Plugin_1.myhook()") - return arg1 + arg2 - - class Plugin_2: - """A 2nd hook implementation namespace.""" - - @simplug.impl - def myhook(self, arg1, arg2): - print("inside Plugin_2.myhook()") - return arg1 - arg2 - - simplug.register(Plugin_1, Plugin_2) - results = simplug.hooks.myhook(arg1=1, arg2=2) - print(results) - -.. code-block:: - - inside Plugin_1.myhook() - inside Plugin_2.myhook() - [3, -1] - -Note that the hooks are executed in the order the plugins are registered. This is different from ``pluggy``. - -A complete example -^^^^^^^^^^^^^^^^^^ - -See ``examples/complete/``. - -Running ``python -m examples.complete`` gets us: - -.. code-block:: - - Your food. Enjoy some egg, egg, egg, salt, pepper, egg, egg - Some condiments? We have pickled walnuts, steak sauce, mushy peas, mint sauce - -After install the plugin: - -.. code-block:: shell - - > pip install --editable examples.complete.plugin - > python -m examples.complete # run again - -.. code-block:: - - Your food. Enjoy some egg, egg, egg, salt, pepper, egg, egg, lovely spam, wonderous spam - Some condiments? We have pickled walnuts, mushy peas, mint sauce, spam sauce - Now this is what I call a condiments tray! - -Usage ------ - -Definition of hooks -^^^^^^^^^^^^^^^^^^^ - -Hooks are specified and implemented by decorating the functions with ``simplug.spec`` and ``simplug.impl`` respectively. - -``simplug`` is initialized by: - -.. code-block:: python - - simplug = Simplug('project') - -The ``'project'`` is a unique name to mark the project, which makes sure ``Simplug('project')`` get the same instance each time. - -Note that if ``simplug`` is initialized without ``project``\ , then a name is generated automatically as such ``project-0``\ , ``project-1``\ , etc. - -Hook specification is marked by ``simplug.spec``\ : - -.. code-block:: python - - simplug = Simplug('project') - - @simplug.spec - def setup(args): - ... - -``simplug.spec`` can take two keyword-arguments: - - -* ``required``\ : Whether this hook is required to be implemented in plugins -* ``result``\ : An enumerator to specify the way to collec the results. - - * SimplugResult.ALL: Get all the results from the hook, as a list - including ``NONE``\ s - * SimplugResult.ALL_BUT_NONE: Get all the results from the hook, - as a list, not including ``NONE``\ s - * SimplugResult.FIRST: Get the none-\ ``None`` result from the - first plugin only (ordered by priority) - * SimplugResult.LAST: Get the none-\ ``None`` result from - the last plugin only - -Hook implementation is marked by ``simplug.impl``\ , which takes no additional arguments. - -The 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. - -Note that default values in implementation functions will be ignored. - -Also 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). - -Loading plugins from setuptools entrypoint -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -You 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. - -The plugin registry -^^^^^^^^^^^^^^^^^^^ - -The 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``. - -The 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. - -If a plugin is loaded from setuptools entrypoint, then the entrypoint name will be used (no matter what name is defined inside the plugin) - -You can enable or disable a plugin temporarily after registration by: - -.. code-block:: python - - simplug.disable('plugin_name') - simplug.enable('plugin_name') - -You can use following methods to inspect the plugin registry: - - -* ``simplug.get_plugin``\ : Get the plugin by name -* ``simplug.get_all_plugins``\ : Get a dictionary of name-plugin mappings of all plugins -* ``simplug.get_all_plugin_names``\ : Get the names of all plugins, in the order it will be executed. -* ``simplug.get_enabled_plugins``\ : Get a dictionary of name-plugin mappings of all enabled plugins -* ``simplug.get_enabled_plugin_names``\ : Get the names of all enabled plugins, in the order it will be executed. - -Calling hooks -^^^^^^^^^^^^^ - -Hooks are call by ``simplug.hooks.()`` and results are collected based on the ``result`` argument passed in ``simplug.spec`` when defining hooks. - -Async hooks -^^^^^^^^^^^ - -It makes no big difference to define an async hook: - -.. code-block:: python - - @simplug.spec - async def async_hook(arg): - ... - - # to supress warnings for sync implementation - @simplug.spec(warn_sync_impl_on_async=False) - async def async_hook(arg): - ... - -One 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``. - -To 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) - -API ---- - -https://pwwang.github.io/simplug/ diff --git a/poetry.lock b/poetry.lock new file mode 100644 index 0000000..96b9d93 --- /dev/null +++ b/poetry.lock @@ -0,0 +1,311 @@ +[[package]] +name = "atomicwrites" +version = "1.4.0" +description = "Atomic file writes." +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" + +[[package]] +name = "attrs" +version = "21.4.0" +description = "Classes Without Boilerplate" +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[package.extras] +dev = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "mypy", "pytest-mypy-plugins", "zope.interface", "furo", "sphinx", "sphinx-notfound-page", "pre-commit", "cloudpickle"] +docs = ["furo", "sphinx", "zope.interface", "sphinx-notfound-page"] +tests = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "mypy", "pytest-mypy-plugins", "zope.interface", "cloudpickle"] +tests_no_zope = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "mypy", "pytest-mypy-plugins", "cloudpickle"] + +[[package]] +name = "colorama" +version = "0.4.4" +description = "Cross-platform colored terminal text." +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[[package]] +name = "coverage" +version = "6.3.2" +description = "Code coverage measurement for Python" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +tomli = {version = "*", optional = true, markers = "extra == \"toml\""} + +[package.extras] +toml = ["tomli"] + +[[package]] +name = "diot" +version = "0.1.6" +description = "Python dictionary with dot notation." +category = "main" +optional = false +python-versions = ">=3.7,<4.0" + +[package.dependencies] +inflection = ">=0.5,<0.6" + +[[package]] +name = "importlib-metadata" +version = "4.11.3" +description = "Read metadata from Python packages" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +typing-extensions = {version = ">=3.6.4", markers = "python_version < \"3.8\""} +zipp = ">=0.5" + +[package.extras] +docs = ["sphinx", "jaraco.packaging (>=9)", "rst.linker (>=1.9)"] +perf = ["ipython"] +testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest-cov", "pytest-enabler (>=1.0.1)", "packaging", "pyfakefs", "flufl.flake8", "pytest-perf (>=0.9.2)", "pytest-black (>=0.3.7)", "pytest-mypy (>=0.9.1)", "importlib-resources (>=1.3)"] + +[[package]] +name = "inflection" +version = "0.5.1" +description = "A port of Ruby on Rails inflector to Python" +category = "main" +optional = false +python-versions = ">=3.5" + +[[package]] +name = "iniconfig" +version = "1.1.1" +description = "iniconfig: brain-dead simple config-ini parsing" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "packaging" +version = "21.3" +description = "Core utilities for Python packages" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +pyparsing = ">=2.0.2,<3.0.5 || >3.0.5" + +[[package]] +name = "pluggy" +version = "1.0.0" +description = "plugin and hook calling mechanisms for python" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} + +[package.extras] +dev = ["pre-commit", "tox"] +testing = ["pytest", "pytest-benchmark"] + +[[package]] +name = "py" +version = "1.11.0" +description = "library with cross-python path, ini-parsing, io, code, log facilities" +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[[package]] +name = "pyparsing" +version = "3.0.9" +description = "pyparsing module - Classes and methods to define and execute parsing grammars" +category = "dev" +optional = false +python-versions = ">=3.6.8" + +[package.extras] +diagrams = ["railroad-diagrams", "jinja2"] + +[[package]] +name = "pytest" +version = "7.1.2" +description = "pytest: simple powerful testing with Python" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +atomicwrites = {version = ">=1.0", markers = "sys_platform == \"win32\""} +attrs = ">=19.2.0" +colorama = {version = "*", markers = "sys_platform == \"win32\""} +importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} +iniconfig = "*" +packaging = "*" +pluggy = ">=0.12,<2.0" +py = ">=1.8.2" +tomli = ">=1.0.0" + +[package.extras] +testing = ["argcomplete", "hypothesis (>=3.56)", "mock", "nose", "pygments (>=2.7.2)", "requests", "xmlschema"] + +[[package]] +name = "pytest-cov" +version = "3.0.0" +description = "Pytest plugin for measuring coverage." +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +coverage = {version = ">=5.2.1", extras = ["toml"]} +pytest = ">=4.6" + +[package.extras] +testing = ["fields", "hunter", "process-tests", "six", "pytest-xdist", "virtualenv"] + +[[package]] +name = "tomli" +version = "2.0.1" +description = "A lil' TOML parser" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "typing-extensions" +version = "4.2.0" +description = "Backported and Experimental Type Hints for Python 3.7+" +category = "main" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "zipp" +version = "3.8.0" +description = "Backport of pathlib-compatible object wrapper for zip files" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.extras] +docs = ["sphinx", "jaraco.packaging (>=9)", "rst.linker (>=1.9)"] +testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest-cov", "pytest-enabler (>=1.0.1)", "jaraco.itertools", "func-timeout", "pytest-black (>=0.3.7)", "pytest-mypy (>=0.9.1)"] + +[metadata] +lock-version = "1.1" +python-versions = "^3.7" +content-hash = "1a3078a4bb0df47355b2be355d897b797af8d4a93f1b8ef0470946b46ff1406a" + +[metadata.files] +atomicwrites = [ + {file = "atomicwrites-1.4.0-py2.py3-none-any.whl", hash = "sha256:6d1784dea7c0c8d4a5172b6c620f40b6e4cbfdf96d783691f2e1302a7b88e197"}, + {file = "atomicwrites-1.4.0.tar.gz", hash = "sha256:ae70396ad1a434f9c7046fd2dd196fc04b12f9e91ffb859164193be8b6168a7a"}, +] +attrs = [ + {file = "attrs-21.4.0-py2.py3-none-any.whl", hash = "sha256:2d27e3784d7a565d36ab851fe94887c5eccd6a463168875832a1be79c82828b4"}, + {file = "attrs-21.4.0.tar.gz", hash = "sha256:626ba8234211db98e869df76230a137c4c40a12d72445c45d5f5b716f076e2fd"}, +] +colorama = [ + {file = "colorama-0.4.4-py2.py3-none-any.whl", hash = "sha256:9f47eda37229f68eee03b24b9748937c7dc3868f906e8ba69fbcbdd3bc5dc3e2"}, + {file = "colorama-0.4.4.tar.gz", hash = "sha256:5941b2b48a20143d2267e95b1c2a7603ce057ee39fd88e7329b0c292aa16869b"}, +] +coverage = [ + {file = "coverage-6.3.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:9b27d894748475fa858f9597c0ee1d4829f44683f3813633aaf94b19cb5453cf"}, + {file = "coverage-6.3.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:37d1141ad6b2466a7b53a22e08fe76994c2d35a5b6b469590424a9953155afac"}, + {file = "coverage-6.3.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f9987b0354b06d4df0f4d3e0ec1ae76d7ce7cbca9a2f98c25041eb79eec766f1"}, + {file = "coverage-6.3.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:26e2deacd414fc2f97dd9f7676ee3eaecd299ca751412d89f40bc01557a6b1b4"}, + {file = "coverage-6.3.2-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4dd8bafa458b5c7d061540f1ee9f18025a68e2d8471b3e858a9dad47c8d41903"}, + {file = "coverage-6.3.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:46191097ebc381fbf89bdce207a6c107ac4ec0890d8d20f3360345ff5976155c"}, + {file = "coverage-6.3.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:6f89d05e028d274ce4fa1a86887b071ae1755082ef94a6740238cd7a8178804f"}, + {file = "coverage-6.3.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:58303469e9a272b4abdb9e302a780072c0633cdcc0165db7eec0f9e32f901e05"}, + {file = "coverage-6.3.2-cp310-cp310-win32.whl", hash = "sha256:2fea046bfb455510e05be95e879f0e768d45c10c11509e20e06d8fcaa31d9e39"}, + {file = "coverage-6.3.2-cp310-cp310-win_amd64.whl", hash = "sha256:a2a8b8bcc399edb4347a5ca8b9b87e7524c0967b335fbb08a83c8421489ddee1"}, + {file = "coverage-6.3.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:f1555ea6d6da108e1999b2463ea1003fe03f29213e459145e70edbaf3e004aaa"}, + {file = "coverage-6.3.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e5f4e1edcf57ce94e5475fe09e5afa3e3145081318e5fd1a43a6b4539a97e518"}, + {file = "coverage-6.3.2-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7a15dc0a14008f1da3d1ebd44bdda3e357dbabdf5a0b5034d38fcde0b5c234b7"}, + {file = "coverage-6.3.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:21b7745788866028adeb1e0eca3bf1101109e2dc58456cb49d2d9b99a8c516e6"}, + {file = "coverage-6.3.2-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:8ce257cac556cb03be4a248d92ed36904a59a4a5ff55a994e92214cde15c5bad"}, + {file = "coverage-6.3.2-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:b0be84e5a6209858a1d3e8d1806c46214e867ce1b0fd32e4ea03f4bd8b2e3359"}, + {file = "coverage-6.3.2-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:acf53bc2cf7282ab9b8ba346746afe703474004d9e566ad164c91a7a59f188a4"}, + {file = "coverage-6.3.2-cp37-cp37m-win32.whl", hash = "sha256:8bdde1177f2311ee552f47ae6e5aa7750c0e3291ca6b75f71f7ffe1f1dab3dca"}, + {file = "coverage-6.3.2-cp37-cp37m-win_amd64.whl", hash = "sha256:b31651d018b23ec463e95cf10070d0b2c548aa950a03d0b559eaa11c7e5a6fa3"}, + {file = "coverage-6.3.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:07e6db90cd9686c767dcc593dff16c8c09f9814f5e9c51034066cad3373b914d"}, + {file = "coverage-6.3.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:2c6dbb42f3ad25760010c45191e9757e7dce981cbfb90e42feef301d71540059"}, + {file = "coverage-6.3.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c76aeef1b95aff3905fb2ae2d96e319caca5b76fa41d3470b19d4e4a3a313512"}, + {file = "coverage-6.3.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8cf5cfcb1521dc3255d845d9dca3ff204b3229401994ef8d1984b32746bb45ca"}, + {file = "coverage-6.3.2-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8fbbdc8d55990eac1b0919ca69eb5a988a802b854488c34b8f37f3e2025fa90d"}, + {file = "coverage-6.3.2-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:ec6bc7fe73a938933d4178c9b23c4e0568e43e220aef9472c4f6044bfc6dd0f0"}, + {file = "coverage-6.3.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:9baff2a45ae1f17c8078452e9e5962e518eab705e50a0aa8083733ea7d45f3a6"}, + {file = "coverage-6.3.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:fd9e830e9d8d89b20ab1e5af09b32d33e1a08ef4c4e14411e559556fd788e6b2"}, + {file = "coverage-6.3.2-cp38-cp38-win32.whl", hash = "sha256:f7331dbf301b7289013175087636bbaf5b2405e57259dd2c42fdcc9fcc47325e"}, + {file = "coverage-6.3.2-cp38-cp38-win_amd64.whl", hash = "sha256:68353fe7cdf91f109fc7d474461b46e7f1f14e533e911a2a2cbb8b0fc8613cf1"}, + {file = "coverage-6.3.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:b78e5afb39941572209f71866aa0b206c12f0109835aa0d601e41552f9b3e620"}, + {file = "coverage-6.3.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:4e21876082ed887baed0146fe222f861b5815455ada3b33b890f4105d806128d"}, + {file = "coverage-6.3.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:34626a7eee2a3da12af0507780bb51eb52dca0e1751fd1471d0810539cefb536"}, + {file = "coverage-6.3.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1ebf730d2381158ecf3dfd4453fbca0613e16eaa547b4170e2450c9707665ce7"}, + {file = "coverage-6.3.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd6fe30bd519694b356cbfcaca9bd5c1737cddd20778c6a581ae20dc8c04def2"}, + {file = "coverage-6.3.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:96f8a1cb43ca1422f36492bebe63312d396491a9165ed3b9231e778d43a7fca4"}, + {file = "coverage-6.3.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:dd035edafefee4d573140a76fdc785dc38829fe5a455c4bb12bac8c20cfc3d69"}, + {file = "coverage-6.3.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:5ca5aeb4344b30d0bec47481536b8ba1181d50dbe783b0e4ad03c95dc1296684"}, + {file = "coverage-6.3.2-cp39-cp39-win32.whl", hash = "sha256:f5fa5803f47e095d7ad8443d28b01d48c0359484fec1b9d8606d0e3282084bc4"}, + {file = "coverage-6.3.2-cp39-cp39-win_amd64.whl", hash = "sha256:9548f10d8be799551eb3a9c74bbf2b4934ddb330e08a73320123c07f95cc2d92"}, + {file = "coverage-6.3.2-pp36.pp37.pp38-none-any.whl", hash = "sha256:18d520c6860515a771708937d2f78f63cc47ab3b80cb78e86573b0a760161faf"}, + {file = "coverage-6.3.2.tar.gz", hash = "sha256:03e2a7826086b91ef345ff18742ee9fc47a6839ccd517061ef8fa1976e652ce9"}, +] +diot = [ + {file = "diot-0.1.6-py3-none-any.whl", hash = "sha256:1e7f97bbc92cbbdd51d8c535885f5e2a71762b364c1b2410dfc84f3a4572d551"}, + {file = "diot-0.1.6.tar.gz", hash = "sha256:1dcfc37dff406c96020d14350c05f920cb7446c3e5abf3477cf2ae0587f72066"}, +] +importlib-metadata = [ + {file = "importlib_metadata-4.11.3-py3-none-any.whl", hash = "sha256:1208431ca90a8cca1a6b8af391bb53c1a2db74e5d1cef6ddced95d4b2062edc6"}, + {file = "importlib_metadata-4.11.3.tar.gz", hash = "sha256:ea4c597ebf37142f827b8f39299579e31685c31d3a438b59f469406afd0f2539"}, +] +inflection = [ + {file = "inflection-0.5.1-py2.py3-none-any.whl", hash = "sha256:f38b2b640938a4f35ade69ac3d053042959b62a0f1076a5bbaa1b9526605a8a2"}, + {file = "inflection-0.5.1.tar.gz", hash = "sha256:1a29730d366e996aaacffb2f1f1cb9593dc38e2ddd30c91250c6dde09ea9b417"}, +] +iniconfig = [ + {file = "iniconfig-1.1.1-py2.py3-none-any.whl", hash = "sha256:011e24c64b7f47f6ebd835bb12a743f2fbe9a26d4cecaa7f53bc4f35ee9da8b3"}, + {file = "iniconfig-1.1.1.tar.gz", hash = "sha256:bc3af051d7d14b2ee5ef9969666def0cd1a000e121eaea580d4a313df4b37f32"}, +] +packaging = [ + {file = "packaging-21.3-py3-none-any.whl", hash = "sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522"}, + {file = "packaging-21.3.tar.gz", hash = "sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb"}, +] +pluggy = [ + {file = "pluggy-1.0.0-py2.py3-none-any.whl", hash = "sha256:74134bbf457f031a36d68416e1509f34bd5ccc019f0bcc952c7b909d06b37bd3"}, + {file = "pluggy-1.0.0.tar.gz", hash = "sha256:4224373bacce55f955a878bf9cfa763c1e360858e330072059e10bad68531159"}, +] +py = [ + {file = "py-1.11.0-py2.py3-none-any.whl", hash = "sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378"}, + {file = "py-1.11.0.tar.gz", hash = "sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719"}, +] +pyparsing = [ + {file = "pyparsing-3.0.9-py3-none-any.whl", hash = "sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc"}, + {file = "pyparsing-3.0.9.tar.gz", hash = "sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb"}, +] +pytest = [ + {file = "pytest-7.1.2-py3-none-any.whl", hash = "sha256:13d0e3ccfc2b6e26be000cb6568c832ba67ba32e719443bfe725814d3c42433c"}, + {file = "pytest-7.1.2.tar.gz", hash = "sha256:a06a0425453864a270bc45e71f783330a7428defb4230fb5e6a731fde06ecd45"}, +] +pytest-cov = [ + {file = "pytest-cov-3.0.0.tar.gz", hash = "sha256:e7f0f5b1617d2210a2cabc266dfe2f4c75a8d32fb89eafb7ad9d06f6d076d470"}, + {file = "pytest_cov-3.0.0-py3-none-any.whl", hash = "sha256:578d5d15ac4a25e5f961c938b85a05b09fdaae9deef3bb6de9a6e766622ca7a6"}, +] +tomli = [ + {file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"}, + {file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"}, +] +typing-extensions = [ + {file = "typing_extensions-4.2.0-py3-none-any.whl", hash = "sha256:6657594ee297170d19f67d55c05852a874e7eb634f4f753dbd667855e07c1708"}, + {file = "typing_extensions-4.2.0.tar.gz", hash = "sha256:f1c24655a0da0d1b67f07e17a5e6b2a105894e6824b92096378bb3668ef02376"}, +] +zipp = [ + {file = "zipp-3.8.0-py3-none-any.whl", hash = "sha256:c4f6e5bbf48e74f7a38e7cc5b0480ff42b0ae5178957d564d18932525d5cf099"}, + {file = "zipp-3.8.0.tar.gz", hash = "sha256:56bf8aadb83c24db6c4b577e13de374ccfb67da2078beba1d037c17980bf43ad"}, +] diff --git a/pyproject.toml b/pyproject.toml index d7d6b15..75372c2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,11 +10,12 @@ readme = "README.md" [tool.poetry.dependencies] python = "^3.7" -diot = "*" +diot = "^0.1" +importlib-metadata = "^4" [tool.poetry.dev-dependencies] -pytest = "*" -pytest-cov = "*" +pytest = "^7" +pytest-cov = "^3" [build-system] requires = ["poetry>=0.12"] diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 4abb018..0000000 --- a/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -diot -pytest -pytest-cov diff --git a/simplug.py b/simplug.py index f19cbcd..c5c6ea3 100644 --- a/simplug.py +++ b/simplug.py @@ -8,15 +8,15 @@ from enum import Enum from diot import OrderedDiot -try: # pragma: no cover +try: # pragma: no cover import importlib_metadata -except ImportError: # pragma: no cover +except ImportError: # pragma: no cover # pylint: disable=ungrouped-imports from importlib import metadata as importlib_metadata -__version__ = '0.0.6' +__version__ = "0.0.6" -SimplugImpl = namedtuple('SimplugImpl', ['impl', 'has_self']) +SimplugImpl = namedtuple("SimplugImpl", ["impl", "has_self"]) SimplugImpl.__doc__ = """A namedtuple wrapper for hook implementation. This is used to mark the method/function to be an implementation of a hook. @@ -25,33 +25,43 @@ impl: The hook implementation """ + class SimplugException(Exception): """Base exception class for simplug""" + class NoSuchPlugin(SimplugException): """When a plugin cannot be imported""" + class PluginRegistered(SimplugException): """When a plugin with a name already registered""" + class NoPluginNameDefined(SimplugException): """When the name of the plugin cannot be found""" + class HookSignatureDifferentFromSpec(SimplugException): """When the hook signature is different from spec""" + class NoSuchHookSpec(SimplugException): """When implemented a undefined hook or calling a non-exist hook""" + class HookRequired(SimplugException): """When a required hook is not implemented""" + class HookSpecExists(SimplugException): """When a hook has already been defined""" + class SyncImplOnAsyncSpecWarning(Warning): """When a sync implementation on an async hook""" + class SimplugResult(Enum): """Way to get the results from the hooks @@ -64,10 +74,12 @@ class SimplugResult(Enum): (ordered by priority) LAST: Get the none-`None` result from the last plugin only """ - ALL = 'all' - ALL_BUT_NONE = 'all_but_none' - FIRST = 'first' - LAST = 'last' + + ALL = "all" + ALL_BUT_NONE = "all_but_none" + FIRST = "first" + LAST = "last" + class SimplugWrapper: """A wrapper for plugin @@ -114,12 +126,14 @@ def __init__(self, plugin: Any, batch_index: int, index: int): else: self.plugin = plugin - priority = getattr(self.plugin, 'priority', None) - self.priority = ((batch_index, index) - if priority is None - else (priority, batch_index)) # type: Tuple[int, int] + priority = getattr(self.plugin, "priority", None) + self.priority = ( + (batch_index, index) + if priority is None + else (priority, batch_index) + ) # type: Tuple[int, int] - self.enabled = True # type: bool + self.enabled = True # type: bool @property def version(self) -> Optional[str]: @@ -129,11 +143,13 @@ def version(self) -> Optional[str]: if `__version__` is defined. If neither is defined, return None. Returns: - In the priority order of plugin.version, plugin.__version__ and None + In the priority order of plugin.version, plugin.__version__ + and None """ - return getattr(self.plugin, - 'version', - getattr(self.plugin, '__version__', None)) + return getattr( + self.plugin, "version", getattr(self.plugin, "__version__", None) + ) + __version__ = version @property @@ -167,10 +183,10 @@ def name(self) -> str: try: return self.plugin.__class__.__name__.lower() - except AttributeError: # pragma: no cover + except AttributeError: # pragma: no cover pass - raise NoPluginNameDefined(str(self.plugin)) # pragma: no cover + raise NoPluginNameDefined(str(self.plugin)) # pragma: no cover def enable(self) -> None: """Enable this plugin""" @@ -204,6 +220,7 @@ def __eq__(self, other: Any) -> bool: def __ne__(self, other: Any) -> bool: return not self.__eq__(other) + class SimplugHook: """A hook of a plugin @@ -222,12 +239,15 @@ class SimplugHook: _has_self: Whether the parameters have `self` as the first. If so, it will be ignored while being called. """ - def __init__(self, # pylint: disable=too-many-arguments - simplug_hooks: "SimplugHooks", - spec: Callable, - required: bool, - result: SimplugResult, - warn_sync_impl_on_async: bool = False): + + def __init__( + self, # pylint: disable=too-many-arguments + simplug_hooks: "SimplugHooks", + spec: Callable, + required: bool, + result: SimplugResult, + warn_sync_impl_on_async: bool = False, + ): self.simplug_hooks = simplug_hooks self.spec = spec self.name = spec.__name__ @@ -249,7 +269,6 @@ def _get_results(self, results: List[Any]) -> Any: # ALL_BUT_NONE return results - def __call__(self, *args, **kwargs): """Call the hook in your system @@ -281,6 +300,7 @@ def __call__(self, *args, **kwargs): return self._get_results(results) + class SimplugHookAsync(SimplugHook): """Wrapper of an async hook""" @@ -322,6 +342,7 @@ async def __call__(self, *args, **kwargs): return self._get_results(results) + class SimplugHooks: """The hooks manager @@ -339,8 +360,8 @@ class SimplugHooks: def __init__(self): - self._registry = OrderedDiot() # type: OrderedDiot - self._specs = {} # type: Dict[str, SimplugHook] + self._registry = OrderedDiot() # type: OrderedDiot + self._specs = {} # type: Dict[str, SimplugHook] self._registry_sorted = False # type: bool def _register(self, plugin: SimplugWrapper) -> None: @@ -354,41 +375,51 @@ def _register(self, plugin: SimplugWrapper) -> None: HookSignatureDifferentFromSpec: When the arguments of a hook implementation is different from its specification """ - if (plugin.name in self._registry and - plugin != self._registry[plugin.name]): - raise PluginRegistered(f'Another plugin named {plugin.name} ' - 'has already been registered.') + if ( + plugin.name in self._registry + and plugin != self._registry[plugin.name] + ): + raise PluginRegistered( + f"Another plugin named {plugin.name} " + "has already been registered." + ) # check if required hooks implemented # and signature for specname, spec in self._specs.items(): hook = plugin.hook(specname) if spec.required and hook is None: - raise HookRequired(f'{specname}, but not implemented ' - f'in plugin {plugin.name}') + raise HookRequired( + f"{specname}, but not implemented " + f"in plugin {plugin.name}" + ) if hook is None: continue impl_params = list(inspect.signature(hook.impl).parameters.keys()) spec_params = list(inspect.signature(spec.spec).parameters.keys()) - if impl_params[0] == 'self': + if impl_params[0] == "self": impl_params = impl_params[1:] - if spec_params[0] == 'self': + if spec_params[0] == "self": spec_params = spec_params[1:] if impl_params != spec_params: raise HookSignatureDifferentFromSpec( - f'{specname!r} in plugin {plugin.name}\n' - f'Expect {spec_params}, ' - f'but got {impl_params}' + f"{specname!r} in plugin {plugin.name}\n" + f"Expect {spec_params}, " + f"but got {impl_params}" ) - if (isinstance(spec, SimplugHookAsync) and - spec.warn_sync_impl_on_async and - not inspect.iscoroutinefunction(hook.impl)): - warnings.warn(f"Sync implementation on async hook " - f"{specname!r} in plugin {plugin.name}", - SyncImplOnAsyncSpecWarning) + if ( + isinstance(spec, SimplugHookAsync) + and spec.warn_sync_impl_on_async + and not inspect.iscoroutinefunction(hook.impl) + ): + warnings.warn( + f"Sync implementation on async hook " + f"{specname!r} in plugin {plugin.name}", + SyncImplOnAsyncSpecWarning, + ) self._registry[plugin.name] = plugin @@ -396,10 +427,9 @@ def _sort_registry(self) -> None: """Sort the registry by the priority only once""" if self._registry_sorted: return - orderedkeys = self._registry.__diot__['orderedkeys'] - self._registry.__diot__['orderedkeys'] = sorted( - orderedkeys, - key=lambda plug: self._registry[plug].priority + orderedkeys = self._registry.__diot__["orderedkeys"] + self._registry.__diot__["orderedkeys"] = sorted( + orderedkeys, key=lambda plug: self._registry[plug].priority ) self._registry_sorted = True @@ -422,6 +452,7 @@ def __getattr__(self, name: str) -> "SimplugHook": exc.__traceback__ ) from None + class SimplugContext: """The context manager for enabling or disabling a set of plugins""" @@ -430,9 +461,10 @@ def __init__(self, simplug: "Simplug", plugins: Optional[Iterable[Any]]): if plugins is not None: self.simplug = simplug self.orig_registry = simplug.hooks._registry.copy() - self.orig_status = {name: plugin.enabled - for name, plugin in self.orig_registry.items()} - + self.orig_status = { + name: plugin.enabled + for name, plugin in self.orig_registry.items() + } def __enter__(self): if self.plugins is None: @@ -466,11 +498,14 @@ def __exit__(self, *exc): for name, status in self.orig_status.items(): self.simplug.hooks._registry[name].enabled = status + class _SimplugContextOnly(SimplugContext): """The context manager with only given plugins enabled""" + class _SimplugContextBut(SimplugContext): """The context manager with only given plugins disabled""" + def __enter__(self): if self.plugins is None: return @@ -496,6 +531,7 @@ def __enter__(self): for plugin in orig_registry.values(): plugin.enable() + class Simplug: """The plugin manager for simplug @@ -521,7 +557,7 @@ def __new__(cls, project: str) -> "Simplug": return cls.PROJECTS[project] def __init__(self, project: str): - if getattr(self, '_inited', None): + if getattr(self, "_inited", None): return self._batch_index = 0 self.hooks = SimplugHooks() @@ -573,8 +609,7 @@ def get_plugin(self, name: str, raw: bool = False) -> object: wrapper = self.hooks._registry[name] return wrapper.plugin if raw else wrapper - def get_all_plugins(self, - raw: bool = False) -> Dict[str, SimplugWrapper]: + def get_all_plugins(self, raw: bool = False) -> Dict[str, SimplugWrapper]: """Get a mapping of all plugins Args: @@ -588,12 +623,16 @@ def get_all_plugins(self, """ if not raw: return self.hooks._registry - return OrderedDiot([(name, plugin.plugin) - for name, plugin - in self.hooks._registry.items()]) + return OrderedDiot( + [ + (name, plugin.plugin) + for name, plugin in self.hooks._registry.items() + ] + ) - def get_enabled_plugins(self, - raw: bool = False) -> Dict[str, SimplugWrapper]: + def get_enabled_plugins( + self, raw: bool = False + ) -> Dict[str, SimplugWrapper]: """Get a mapping of all enabled plugins Args: @@ -605,10 +644,13 @@ def get_enabled_plugins(self, Returns: The mapping of all enabled plugins """ - return OrderedDiot([(name, plugin.plugin if raw else plugin) - for name, plugin - in self.hooks._registry.items() - if plugin.enabled]) + return OrderedDiot( + [ + (name, plugin.plugin if raw else plugin) + for name, plugin in self.hooks._registry.items() + if plugin.enabled + ] + ) def get_all_plugin_names(self) -> List[str]: """Get the names of all plugins @@ -624,12 +666,14 @@ def get_enabled_plugin_names(self) -> List[str]: Returns: The names of all enabled plugins """ - return [name for name, plugin in self.hooks._registry.items() - if plugin.enabled] + return [ + name + for name, plugin in self.hooks._registry.items() + if plugin.enabled + ] def plugins_only_context( - self, - plugins: Optional[Iterable[Any]] + self, plugins: Optional[Iterable[Any]] ) -> _SimplugContextOnly: """A context manager with only given plugins enabled @@ -644,8 +688,7 @@ def plugins_only_context( return _SimplugContextOnly(self, plugins) def plugins_but_context( - self, - plugins: Optional[Iterable[Any]] + self, plugins: Optional[Iterable[Any]] ) -> _SimplugContextBut: """A context manager with all plugins but given plugins enabled @@ -677,11 +720,13 @@ def disable(self, *names: str) -> None: for name in names: self.get_plugin(name).disable() - def spec(self, - hook: Optional[Callable] = None, - required: bool = False, - result: SimplugResult = SimplugResult.ALL_BUT_NONE, - warn_sync_impl_on_async: bool = True) -> Callable: + def spec( + self, + hook: Optional[Callable] = None, + required: bool = False, + result: SimplugResult = SimplugResult.ALL_BUT_NONE, + warn_sync_impl_on_async: bool = True, + ) -> Callable: """A decorator to define the specification of a hook Args: @@ -699,6 +744,7 @@ def spec(self, A decorator function of other argument is passed, or the hook spec itself. """ + def decorator(hook_func: Callable): hook_name = hook_func.__name__ if hook_name in self.hooks._specs: @@ -706,8 +752,11 @@ def decorator(hook_func: Callable): if inspect.iscoroutinefunction(hook_func): self.hooks._specs[hook_name] = SimplugHookAsync( - self.hooks, hook_func, required, result, - warn_sync_impl_on_async + self.hooks, + hook_func, + required, + result, + warn_sync_impl_on_async, ) else: self.hooks._specs[hook_name] = SimplugHook( @@ -732,4 +781,4 @@ def impl(self, hook: Callable): """ if hook.__name__ not in self.hooks._specs: raise NoSuchHookSpec(hook.__name__) - return SimplugImpl(hook, 'self' in inspect.signature(hook).parameters) + return SimplugImpl(hook, "self" in inspect.signature(hook).parameters)