From 2c009ff86975f9810a1127a9f242235c597a7a89 Mon Sep 17 00:00:00 2001 From: Ronny Pfannschmidt Date: Wed, 22 Jul 2026 12:24:41 +0200 Subject: [PATCH 1/5] chore(structure): split hook modules into role-specific files Move hook types, markers, callers, implementations, and multicall out of the monolithic _hooks/_callers modules so later typed-config and CompletionHook work can land without thrashing one huge file. Keep _hooks and _callers as re-export shims for import compatibility. Co-authored-by: Cursor AI Co-authored-by: Cursor Grok 4.5 --- CHANGELOG.rst | 6 +- changelog/703.trivial.rst | 4 + src/pluggy/_caller.py | 312 +++++++++++++++ src/pluggy/_callers.py | 183 +-------- src/pluggy/_config.py | 54 +++ src/pluggy/_decorators.py | 353 +++++++++++++++++ src/pluggy/_execution.py | 174 +++++++++ src/pluggy/_hooks.py | 785 ++------------------------------------ src/pluggy/_impl.py | 80 ++++ 9 files changed, 1036 insertions(+), 915 deletions(-) create mode 100644 changelog/703.trivial.rst create mode 100644 src/pluggy/_caller.py create mode 100644 src/pluggy/_config.py create mode 100644 src/pluggy/_decorators.py create mode 100644 src/pluggy/_execution.py create mode 100644 src/pluggy/_impl.py diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 683b399f..061d025a 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -222,7 +222,7 @@ Features .. code-block:: python - def my_hook_implementation(arg): + def my_hook_impl(arg): print("before") yield print("after") @@ -230,7 +230,7 @@ Features @hookimpl(hookwrapper=True) def my_hook(arg): - return my_hook_implementation(arg) + return my_hook_impl(arg) change it to use ``yield from`` instead: @@ -238,7 +238,7 @@ Features @hookimpl(hookwrapper=True) def my_hook(arg): - yield from my_hook_implementation(arg) + yield from my_hook_impl(arg) - `#309 `_: Add official support for Python 3.9. diff --git a/changelog/703.trivial.rst b/changelog/703.trivial.rst new file mode 100644 index 00000000..14ec81aa --- /dev/null +++ b/changelog/703.trivial.rst @@ -0,0 +1,4 @@ +The internal ``pluggy._hooks`` module was split into role-specific modules +(``_caller``, ``_config``, ``_decorators``, ``_execution`` and ``_impl``). +``pluggy._hooks`` remains as a re-export shim, and the public API is +unchanged. diff --git a/src/pluggy/_caller.py b/src/pluggy/_caller.py new file mode 100644 index 00000000..ea95b800 --- /dev/null +++ b/src/pluggy/_caller.py @@ -0,0 +1,312 @@ +""" +Hook callers and relay. +""" + +from __future__ import annotations + +from collections.abc import Callable +from collections.abc import Mapping +from collections.abc import Sequence +from collections.abc import Set as AbstractSet +from typing import Any +from typing import Final +from typing import final +from typing import TYPE_CHECKING +from typing import TypeAlias +import warnings + +from ._config import HookimplOpts +from ._config import HookspecOpts +from ._decorators import _Namespace +from ._decorators import HookSpec +from ._impl import _Plugin +from ._impl import HookImpl + + +_HookExec: TypeAlias = Callable[ + [str, Sequence[HookImpl], Mapping[str, object], bool], + object | list[object], +] + + +@final +class HookRelay: + """Hook holder object for performing 1:N hook calls where N is the number + of registered plugins.""" + + __slots__ = ("__dict__",) + + def __init__(self) -> None: + """:meta private:""" + + if TYPE_CHECKING: + + def __getattr__(self, name: str) -> HookCaller: ... + + +# Historical name (pluggy<=1.2), kept for backward compatibility. +_HookRelay = HookRelay + + +_CallHistory: TypeAlias = list[ + tuple[Mapping[str, object], Callable[[Any], None] | None] +] + + +class HookCaller: + """A caller of all registered implementations of a hook specification.""" + + __slots__ = ( + "_call_history", + "_hookexec", + "_hookimpls", + "name", + "spec", + ) + + def __init__( + self, + name: str, + hook_execute: _HookExec, + specmodule_or_class: _Namespace | None = None, + spec_opts: HookspecOpts | None = None, + ) -> None: + """:meta private:""" + #: Name of the hook getting called. + self.name: Final = name + self._hookexec: Final = hook_execute + # The hookimpls list. The caller iterates it *in reverse*. Format: + # 1. trylast nonwrappers + # 2. nonwrappers + # 3. tryfirst nonwrappers + # 4. trylast wrappers + # 5. wrappers + # 6. tryfirst wrappers + self._hookimpls: Final[list[HookImpl]] = [] + self._call_history: _CallHistory | None = None + # TODO: Document, or make private. + self.spec: HookSpec | None = None + if specmodule_or_class is not None: + assert spec_opts is not None + self.set_specification(specmodule_or_class, spec_opts) + + # TODO: Document, or make private. + def has_spec(self) -> bool: + return self.spec is not None + + # TODO: Document, or make private. + def set_specification( + self, + specmodule_or_class: _Namespace, + spec_opts: HookspecOpts, + ) -> None: + if self.spec is not None: + raise ValueError( + f"Hook {self.spec.name!r} is already registered " + f"within namespace {self.spec.namespace}" + ) + self.spec = HookSpec(specmodule_or_class, self.name, spec_opts) + if spec_opts.get("historic"): + self._call_history = [] + + def is_historic(self) -> bool: + """Whether this caller is :ref:`historic `.""" + return self._call_history is not None + + def _remove_plugin(self, plugin: _Plugin) -> None: + """Remove all hook implementations registered by the given plugin.""" + remaining = [impl for impl in self._hookimpls if impl.plugin != plugin] + if len(remaining) == len(self._hookimpls): + raise ValueError(f"plugin {plugin!r} not found") + self._hookimpls[:] = remaining + + def get_hookimpls(self) -> list[HookImpl]: + """Get all registered hook implementations for this hook.""" + return self._hookimpls.copy() + + def _add_hookimpl(self, hookimpl: HookImpl) -> None: + """Add an implementation to the callback chain.""" + for i, method in enumerate(self._hookimpls): + if method.hookwrapper or method.wrapper: + splitpoint = i + break + else: + splitpoint = len(self._hookimpls) + if hookimpl.hookwrapper or hookimpl.wrapper: + start, end = splitpoint, len(self._hookimpls) + else: + start, end = 0, splitpoint + + if hookimpl.trylast: + self._hookimpls.insert(start, hookimpl) + elif hookimpl.tryfirst: + self._hookimpls.insert(end, hookimpl) + else: + # find last non-tryfirst method + i = end - 1 + while i >= start and self._hookimpls[i].tryfirst: + i -= 1 + self._hookimpls.insert(i + 1, hookimpl) + + def __repr__(self) -> str: + return f"" + + def _verify_all_args_are_provided(self, kwargs: Mapping[str, object]) -> None: + # This is written to avoid expensive operations when not needed. + if self.spec: + for argname in self.spec.argnames: + if argname not in kwargs: + notincall = ", ".join( + repr(argname) + for argname in self.spec.argnames + # Avoid self.spec.argnames - kwargs.keys() + # it doesn't preserve order. + if argname not in kwargs + ) + warnings.warn( + f"Argument(s) {notincall} which are declared in the hookspec " + "cannot be found in this hook call", + # 3, not 2: the warning is raised in this helper, which + # is called by __call__/call_historic/call_extra, which + # are called by the code making the hook call. + stacklevel=3, + ) + break + + def __call__(self, **kwargs: object) -> Any: + """Call the hook. + + Only accepts keyword arguments, which should match the hook + specification. + + Returns the result(s) of calling all registered plugins, see + :ref:`calling`. + """ + assert not self.is_historic(), ( + "Cannot directly call a historic hook - use call_historic instead." + ) + self._verify_all_args_are_provided(kwargs) + firstresult = self.spec.opts.get("firstresult", False) if self.spec else False + # Copy because plugins may register other plugins during iteration (#438). + return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) + + def call_historic( + self, + result_callback: Callable[[Any], None] | None = None, + kwargs: Mapping[str, object] | None = None, + ) -> None: + """Call the hook with given ``kwargs`` for all registered plugins and + for all plugins which will be registered afterwards, see + :ref:`historic`. + + :param result_callback: + If provided, will be called for each non-``None`` result obtained + from a hook implementation. + """ + assert self._call_history is not None + kwargs = kwargs or {} + self._verify_all_args_are_provided(kwargs) + self._call_history.append((kwargs, result_callback)) + # Historizing hooks don't return results. + # Remember firstresult isn't compatible with historic. + # Copy because plugins may register other plugins during iteration (#438). + res = self._hookexec(self.name, self._hookimpls.copy(), kwargs, False) + if result_callback is None: + return + if isinstance(res, list): + for x in res: + result_callback(x) + + def call_extra( + self, methods: Sequence[Callable[..., object]], kwargs: Mapping[str, object] + ) -> Any: + """Call the hook with some additional temporarily participating + methods using the specified ``kwargs`` as call parameters, see + :ref:`call_extra`.""" + assert not self.is_historic(), ( + "Cannot directly call a historic hook - use call_historic instead." + ) + self._verify_all_args_are_provided(kwargs) + opts: HookimplOpts = { + "wrapper": False, + "hookwrapper": False, + "optionalhook": False, + "trylast": False, + "tryfirst": False, + "specname": None, + } + hookimpls = self._hookimpls.copy() + for method in methods: + hookimpl = HookImpl(None, "", method, opts) + # Find last non-tryfirst nonwrapper method. + i = len(hookimpls) - 1 + while i >= 0 and ( + # Skip wrappers. + (hookimpls[i].hookwrapper or hookimpls[i].wrapper) + # Skip tryfirst nonwrappers. + or hookimpls[i].tryfirst + ): + i -= 1 + hookimpls.insert(i + 1, hookimpl) + firstresult = self.spec.opts.get("firstresult", False) if self.spec else False + return self._hookexec(self.name, hookimpls, kwargs, firstresult) + + def _maybe_apply_history(self, method: HookImpl) -> None: + """Apply call history to a new hookimpl if it is marked as historic.""" + if self.is_historic(): + assert self._call_history is not None + for kwargs, result_callback in self._call_history: + res = self._hookexec(self.name, [method], kwargs, False) + if res and result_callback is not None: + # XXX: remember firstresult isn't compat with historic + assert isinstance(res, list) + result_callback(res[0]) + + +# Historical name (pluggy<=1.2), kept for backward compatibility. +_HookCaller = HookCaller + + +class _SubsetHookCaller(HookCaller): + """A proxy to another HookCaller which manages calls to all registered + plugins except the ones from remove_plugins.""" + + # This class is unusual: in inhertits from `HookCaller` so all of + # the *code* runs in the class, but it delegates all underlying *data* + # to the original HookCaller. + # `subset_hook_caller` used to be implemented by creating a full-fledged + # HookCaller, copying all hookimpls from the original. This had problems + # with memory leaks (#346) and historic calls (#347), which make a proxy + # approach better. + # An alternative implementation is to use a `_getattr__`/`__getattribute__` + # proxy, however that adds more overhead and is more tricky to implement. + + __slots__ = ( + "_orig", + "_remove_plugins", + ) + + def __init__(self, orig: HookCaller, remove_plugins: AbstractSet[_Plugin]) -> None: + self._orig = orig + self._remove_plugins = remove_plugins + self.name = orig.name # type: ignore[misc] + self._hookexec = orig._hookexec # type: ignore[misc] + + @property # type: ignore[misc] + def _hookimpls(self) -> list[HookImpl]: + return [ + impl + for impl in self._orig._hookimpls + if impl.plugin not in self._remove_plugins + ] + + @property + def spec(self) -> HookSpec | None: # type: ignore[override] + return self._orig.spec + + @property + def _call_history(self) -> _CallHistory | None: # type: ignore[override] + return self._orig._call_history + + def __repr__(self) -> str: + return f"<_SubsetHookCaller {self.name!r}>" diff --git a/src/pluggy/_callers.py b/src/pluggy/_callers.py index 8b4b1477..1bde1185 100644 --- a/src/pluggy/_callers.py +++ b/src/pluggy/_callers.py @@ -1,174 +1,23 @@ """ -Call loop machinery +Call loop machinery. + +This module re-exports the execution engine for backward compatibility. +Prefer importing from :mod:`pluggy._execution`. """ from __future__ import annotations -from collections.abc import Generator -from collections.abc import Mapping -from collections.abc import Sequence -from typing import cast -from typing import NoReturn -from typing import TYPE_CHECKING -from typing import TypeAlias -import warnings - -from ._hooks import HookImpl -from ._result import HookCallError -from ._result import Result -from ._warnings import PluggyTeardownRaisedWarning - - -# Need to distinguish between old- and new-style hook wrappers. -# Wrapping with a tuple is the fastest type-safe way I found to do it. -Teardown: TypeAlias = Generator[None, object, object] - - -def run_old_style_hookwrapper( - hook_impl: HookImpl, hook_name: str, args: Sequence[object] -) -> Teardown: - """ - backward compatibility wrapper to run a old style hookwrapper as a wrapper - """ - if TYPE_CHECKING: - teardown = cast(Teardown, hook_impl.function(*args)) - else: - teardown = hook_impl.function(*args) - try: - next(teardown) - except StopIteration: - _raise_wrapfail(teardown, "did not yield") - try: - res = yield - result = Result(res, None) - except BaseException as exc: - result = Result(None, exc) - try: - teardown.send(result) - except StopIteration: - pass - except BaseException as e: - _warn_teardown_exception(hook_name, hook_impl, e) - raise - else: - _raise_wrapfail(teardown, "has second yield") - finally: - teardown.close() - return result.get_result() - - -def _raise_wrapfail( - wrap_controller: Generator[None, object, object], - msg: str, -) -> NoReturn: - co = wrap_controller.gi_code # type: ignore[attr-defined] - raise RuntimeError( - f"wrap_controller at {co.co_name!r} {co.co_filename}:{co.co_firstlineno} {msg}" - ) - - -def _warn_teardown_exception( - hook_name: str, hook_impl: HookImpl, e: BaseException -) -> None: - msg = ( - f"A plugin raised an exception during an old-style hookwrapper teardown.\n" - f"Plugin: {hook_impl.plugin_name}, Hook: {hook_name}\n" - f"{type(e).__name__}: {e}\n" - f"For more information see https://pluggy.readthedocs.io/en/stable/api_reference.html#pluggy.PluggyTeardownRaisedWarning" - ) - warnings.warn(PluggyTeardownRaisedWarning(msg), stacklevel=6) - - -def _multicall( - hook_name: str, - hook_impls: Sequence[HookImpl], - caller_kwargs: Mapping[str, object], - firstresult: bool, -) -> object | list[object]: - """Execute a call into multiple python functions/methods and return the - result(s). - - ``caller_kwargs`` comes from HookCaller.__call__(). - """ - __tracebackhide__ = True - results: list[object] = [] - exception = None - teardowns: list[Teardown] = [] - try: # run impl and wrapper setup functions in a loop - for hook_impl in reversed(hook_impls): - try: - args = [caller_kwargs[argname] for argname in hook_impl.argnames] - except KeyError as e: - raise HookCallError( - f"hook call must provide argument {e.args[0]!r}" - ) from e - - if hook_impl.hookwrapper: - function_gen = run_old_style_hookwrapper(hook_impl, hook_name, args) - - next(function_gen) # first yield - teardowns.append(function_gen) - - elif hook_impl.wrapper: - res = hook_impl.function(*args) - # If this cast is not valid, a type error is raised below, - # which is the desired response. - if TYPE_CHECKING: - function_gen = cast(Generator[None, object, object], res) - else: - function_gen = res - try: - next(function_gen) # first yield - except StopIteration: - _raise_wrapfail(function_gen, "did not yield") - teardowns.append(function_gen) - else: - res = hook_impl.function(*args) - if res is not None: - results.append(res) - if firstresult: # halt further impl calls - break - except BaseException as exc: - exception = exc - finally: - if firstresult: # first result hooks return a single value - result = results[0] if results else None - else: - result = results +from ._execution import _multicall +from ._execution import _raise_wrapfail +from ._execution import _warn_teardown_exception +from ._execution import run_old_style_hookwrapper +from ._execution import Teardown - # run all wrapper post-yield blocks - for teardown in reversed(teardowns): - try: - if exception is not None: - try: - teardown.throw(exception) - except RuntimeError as re: - # StopIteration from generator causes RuntimeError - # even for coroutine usage - see #544 - if ( - isinstance(exception, StopIteration) - and re.__cause__ is exception - ): - teardown.close() - continue - else: - raise - else: - teardown.send(result) - # Following is unreachable for a well behaved hook wrapper. - # Try to force finalizers otherwise postponed till GC action. - # Note: close() may raise if generator handles GeneratorExit. - teardown.close() - except StopIteration as si: - result = si.value - exception = None - continue - except BaseException as e: - exception = e - continue - _raise_wrapfail(teardown, "has second yield") - if exception is not None: - raise exception - else: - return result +__all__ = [ + "Teardown", + "_multicall", + "_raise_wrapfail", + "_warn_teardown_exception", + "run_old_style_hookwrapper", +] diff --git a/src/pluggy/_config.py b/src/pluggy/_config.py new file mode 100644 index 00000000..576a7794 --- /dev/null +++ b/src/pluggy/_config.py @@ -0,0 +1,54 @@ +""" +Configuration types for hook specifications and implementations. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TypedDict + + +class HookspecOpts(TypedDict): + """Options for a hook specification.""" + + #: Whether the hook is :ref:`first result only `. + firstresult: bool + #: Whether the hook is :ref:`historic `. + historic: bool + #: Whether the hook :ref:`warns when implemented `. + warn_on_impl: Warning | None + #: Whether the hook warns when :ref:`certain arguments are requested + #: `. + #: + #: .. versionadded:: 1.5 + warn_on_impl_args: Mapping[str, Warning] | None + + +class HookimplOpts(TypedDict): + """Options for a hook implementation.""" + + #: Whether the hook implementation is a :ref:`wrapper `. + wrapper: bool + #: Whether the hook implementation is an :ref:`old-style wrapper + #: `. + hookwrapper: bool + #: Whether validation against a hook specification is :ref:`optional + #: `. + optionalhook: bool + #: Whether to try to order this hook implementation :ref:`first + #: `. + tryfirst: bool + #: Whether to try to order this hook implementation :ref:`last + #: `. + trylast: bool + #: The name of the hook specification to match, see :ref:`specname`. + specname: str | None + + +def normalize_hookimpl_opts(opts: HookimplOpts) -> None: + opts.setdefault("tryfirst", False) + opts.setdefault("trylast", False) + opts.setdefault("wrapper", False) + opts.setdefault("hookwrapper", False) + opts.setdefault("optionalhook", False) + opts.setdefault("specname", None) diff --git a/src/pluggy/_decorators.py b/src/pluggy/_decorators.py new file mode 100644 index 00000000..98f1409e --- /dev/null +++ b/src/pluggy/_decorators.py @@ -0,0 +1,353 @@ +""" +Hook markers, specifications, and related helpers. +""" + +from __future__ import annotations + +from collections.abc import Callable +from collections.abc import Mapping +import inspect +import sys +import types +from types import ModuleType +from typing import Final +from typing import final +from typing import overload +from typing import TypeAlias +from typing import TypeVar +import warnings + +from ._config import HookimplOpts +from ._config import HookspecOpts + + +_F = TypeVar("_F", bound=Callable[..., object]) + +_Namespace: TypeAlias = ModuleType | type + + +@final +class HookspecMarker: + """Decorator for marking functions as hook specifications. + + Instantiate it with a project_name to get a decorator. + Calling :meth:`PluginManager.add_hookspecs` later will discover all marked + functions if the :class:`PluginManager` uses the same project name. + """ + + __slots__ = ("project_name",) + + def __init__(self, project_name: str) -> None: + self.project_name: Final = project_name + + @overload + def __call__( + self, + function: _F, + firstresult: bool = False, + historic: bool = False, + warn_on_impl: Warning | None = None, + warn_on_impl_args: Mapping[str, Warning] | None = None, + ) -> _F: ... + + @overload + def __call__( + self, + function: None = ..., + firstresult: bool = ..., + historic: bool = ..., + warn_on_impl: Warning | None = ..., + warn_on_impl_args: Mapping[str, Warning] | None = ..., + ) -> Callable[[_F], _F]: ... + + def __call__( + self, + function: _F | None = None, + firstresult: bool = False, + historic: bool = False, + warn_on_impl: Warning | None = None, + warn_on_impl_args: Mapping[str, Warning] | None = None, + ) -> _F | Callable[[_F], _F]: + """If passed a function, directly sets attributes on the function + which will make it discoverable to :meth:`PluginManager.add_hookspecs`. + + If passed no function, returns a decorator which can be applied to a + function later using the attributes supplied. + + :param firstresult: + If ``True``, the 1:N hook call (N being the number of registered + hook implementation functions) will stop at I<=N when the I'th + function returns a non-``None`` result. See :ref:`firstresult`. + + :param historic: + If ``True``, every call to the hook will be memorized and replayed + on plugins registered after the call was made. See :ref:`historic`. + + :param warn_on_impl: + If given, every implementation of this hook will trigger the given + warning. See :ref:`warn_on_impl`. + + :param warn_on_impl_args: + If given, every implementation of this hook which requests one of + the arguments in the dict will trigger the corresponding warning. + See :ref:`warn_on_impl`. + + .. versionadded:: 1.5 + """ + + def setattr_hookspec_opts(func: _F) -> _F: + if historic and firstresult: + raise ValueError("cannot have a historic firstresult hook") + opts: HookspecOpts = { + "firstresult": firstresult, + "historic": historic, + "warn_on_impl": warn_on_impl, + "warn_on_impl_args": warn_on_impl_args, + } + setattr(func, self.project_name + "_spec", opts) + return func + + if function is not None: + return setattr_hookspec_opts(function) + else: + return setattr_hookspec_opts + + +@final +class HookimplMarker: + """Decorator for marking functions as hook implementations. + + Instantiate it with a ``project_name`` to get a decorator. + Calling :meth:`PluginManager.register` later will discover all marked + functions if the :class:`PluginManager` uses the same project name. + """ + + __slots__ = ("project_name",) + + def __init__(self, project_name: str) -> None: + self.project_name: Final = project_name + + @overload + def __call__( + self, + function: _F, + hookwrapper: bool = ..., + optionalhook: bool = ..., + tryfirst: bool = ..., + trylast: bool = ..., + specname: str | None = ..., + wrapper: bool = ..., + ) -> _F: ... + + @overload + def __call__( + self, + function: None = ..., + hookwrapper: bool = ..., + optionalhook: bool = ..., + tryfirst: bool = ..., + trylast: bool = ..., + specname: str | None = ..., + wrapper: bool = ..., + ) -> Callable[[_F], _F]: ... + + def __call__( + self, + function: _F | None = None, + hookwrapper: bool = False, + optionalhook: bool = False, + tryfirst: bool = False, + trylast: bool = False, + specname: str | None = None, + wrapper: bool = False, + ) -> _F | Callable[[_F], _F]: + """If passed a function, directly sets attributes on the function + which will make it discoverable to :meth:`PluginManager.register`. + + If passed no function, returns a decorator which can be applied to a + function later using the attributes supplied. + + :param optionalhook: + If ``True``, a missing matching hook specification will not result + in an error (by default it is an error if no matching spec is + found). See :ref:`optionalhook`. + + :param tryfirst: + If ``True``, this hook implementation will run as early as possible + in the chain of N hook implementations for a specification. See + :ref:`callorder`. + + :param trylast: + If ``True``, this hook implementation will run as late as possible + in the chain of N hook implementations for a specification. See + :ref:`callorder`. + + :param wrapper: + If ``True`` ("new-style hook wrapper"), the hook implementation + needs to execute exactly one ``yield``. The code before the + ``yield`` is run early before any non-hook-wrapper function is run. + The code after the ``yield`` is run after all non-hook-wrapper + functions have run. The ``yield`` receives the result value of the + inner calls, or raises the exception of inner calls (including + earlier hook wrapper calls). The return value of the function + becomes the return value of the hook, and a raised exception becomes + the exception of the hook. See :ref:`hookwrapper`. + + :param hookwrapper: + If ``True`` ("old-style hook wrapper"), the hook implementation + needs to execute exactly one ``yield``. The code before the + ``yield`` is run early before any non-hook-wrapper function is run. + The code after the ``yield`` is run after all non-hook-wrapper + function have run The ``yield`` receives a :class:`Result` object + representing the exception or result outcome of the inner calls + (including earlier hook wrapper calls). This option is mutually + exclusive with ``wrapper``. See :ref:`old_style_hookwrapper`. + + :param specname: + If provided, the given name will be used instead of the function + name when matching this hook implementation to a hook specification + during registration. See :ref:`specname`. + + .. versionadded:: 1.2.0 + The ``wrapper`` parameter. + """ + + def setattr_hookimpl_opts(func: _F) -> _F: + opts: HookimplOpts = { + "wrapper": wrapper, + "hookwrapper": hookwrapper, + "optionalhook": optionalhook, + "tryfirst": tryfirst, + "trylast": trylast, + "specname": specname, + } + setattr(func, self.project_name + "_impl", opts) + return func + + if function is None: + return setattr_hookimpl_opts + else: + return setattr_hookimpl_opts(function) + + +_PYPY = sys.implementation.name == "pypy" +_IMPLICIT_NAMES = ("self", "cls", "obj") if _PYPY else ("self", "cls") + +# Qualnames whose missing-self deprecation warning is suppressed because +# their upstream code is already fixed but not yet released. +# Remove entries once a release with the fix is available. +_NOSELF_WARN_SUPPRESS: frozenset[str] = frozenset( + { + # pytest-timeout >=2.3.2 has the fix, but is unreleased as of 2026-05. + "TimeoutHooks.pytest_timeout_set_timer", + "TimeoutHooks.pytest_timeout_cancel_timer", + } +) + + +def varnames( + func: object, *, legacy_noself: bool = False +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Return tuple of positional and keyword parameter names for a callable. + + In case of a class, its ``__init__`` method is considered. + For bound methods, the already-bound first parameter is not included. + For unbound methods with a dotted ``__qualname__``, the first parameter is + stripped only if its name is a known implicit name (``self``, ``cls``). + Keyword-only parameters are not included. + + :param legacy_noself: + If ``True``, support hookspec classes whose methods omit ``self``. + When the function looks like a class method but has no implicit first + parameter, a :class:`DeprecationWarning` is emitted. + """ + is_bound = False + if inspect.isclass(func): + try: + func = func.__init__ + except AttributeError: # pragma: no cover - pypy special case + return (), () + is_bound = True + elif not inspect.isroutine(func): # callable object? + try: + # Not a `callable()` check: the `__call__` attribute itself is + # wanted, so that its signature can be inspected below. + func = getattr(func, "__call__", func) # noqa: B004 + except Exception: # pragma: no cover - pypy special case + return (), () + + # Track bound methods before unwrapping, since __func__ loses that info. + if inspect.ismethod(func): + is_bound = True + func = inspect.unwrap(func) # type: ignore[arg-type] + if inspect.ismethod(func): + is_bound = True + func = func.__func__ + + try: + code: types.CodeType = func.__code__ # type: ignore[attr-defined] + defaults: tuple[object, ...] | None = func.__defaults__ # type: ignore[attr-defined] + qualname: str = func.__qualname__ # type: ignore[attr-defined] + except AttributeError: # pragma: no cover + return (), () + + # Get positional argument names (positional-only + positional-or-keyword) + args: tuple[str, ...] = code.co_varnames[: code.co_argcount] + + # Determine which args have defaults + kwargs: tuple[str, ...] + if defaults: + index = -len(defaults) + args, kwargs = args[:index], args[index:] + else: + kwargs = () + + # Strip implicit instance/class arg. + # Check if this looks like a method defined in a class by examining the + # qualname after the last "." segment (if any). A remaining dot + # means it's a class method (e.g. "MyClass.method" or + # "func..MyClass.method"), not just a nested function. + _tail = qualname.rsplit(".", maxsplit=1)[-1] + _is_class_method = "." in _tail + if args: + if is_bound or (_is_class_method and args[0] in _IMPLICIT_NAMES): + args = args[1:] + elif _is_class_method and legacy_noself and _tail not in _NOSELF_WARN_SUPPRESS: + warnings.warn( + f"{qualname} is a method but its first parameter" + f" {args[0]!r} is not 'self'." + f" Add 'self' as the first parameter or use @staticmethod." + f" This will become an error in a future version of pluggy.", + DeprecationWarning, + stacklevel=2, + ) + + return args, kwargs + + +@final +class HookSpec: + __slots__ = ( + "argnames", + "function", + "kwargnames", + "name", + "namespace", + "opts", + "warn_on_impl", + "warn_on_impl_args", + ) + + def __init__(self, namespace: _Namespace, name: str, opts: HookspecOpts) -> None: + self.namespace = namespace + self.name = name + self.function: Callable[..., object] = getattr(namespace, name) + legacy_noself = inspect.isclass(namespace) and not isinstance( + inspect.getattr_static(namespace, name), staticmethod + ) + self.argnames, self.kwargnames = varnames( + self.function, legacy_noself=legacy_noself + ) + self.opts = opts + self.warn_on_impl = opts.get("warn_on_impl") + self.warn_on_impl_args = opts.get("warn_on_impl_args") diff --git a/src/pluggy/_execution.py b/src/pluggy/_execution.py new file mode 100644 index 00000000..cda5210d --- /dev/null +++ b/src/pluggy/_execution.py @@ -0,0 +1,174 @@ +""" +Hook call execution (multicall) machinery. +""" + +from __future__ import annotations + +from collections.abc import Generator +from collections.abc import Mapping +from collections.abc import Sequence +from typing import cast +from typing import NoReturn +from typing import TYPE_CHECKING +from typing import TypeAlias +import warnings + +from ._impl import HookImpl +from ._result import HookCallError +from ._result import Result +from ._warnings import PluggyTeardownRaisedWarning + + +# Need to distinguish between old- and new-style hook wrappers. +# Wrapping with a tuple is the fastest type-safe way I found to do it. +Teardown: TypeAlias = Generator[None, object, object] + + +def run_old_style_hookwrapper( + hook_impl: HookImpl, hook_name: str, args: Sequence[object] +) -> Teardown: + """ + backward compatibility wrapper to run a old style hookwrapper as a wrapper + """ + if TYPE_CHECKING: + teardown = cast(Teardown, hook_impl.function(*args)) + else: + teardown = hook_impl.function(*args) + try: + next(teardown) + except StopIteration: + _raise_wrapfail(teardown, "did not yield") + try: + res = yield + result = Result(res, None) + except BaseException as exc: + result = Result(None, exc) + try: + teardown.send(result) + except StopIteration: + pass + except BaseException as e: + _warn_teardown_exception(hook_name, hook_impl, e) + raise + else: + _raise_wrapfail(teardown, "has second yield") + finally: + teardown.close() + return result.get_result() + + +def _raise_wrapfail( + wrap_controller: Generator[None, object, object], + msg: str, +) -> NoReturn: + co = wrap_controller.gi_code # type: ignore[attr-defined] + raise RuntimeError( + f"wrap_controller at {co.co_name!r} {co.co_filename}:{co.co_firstlineno} {msg}" + ) + + +def _warn_teardown_exception( + hook_name: str, hook_impl: HookImpl, e: BaseException +) -> None: + msg = ( + f"A plugin raised an exception during an old-style hookwrapper teardown.\n" + f"Plugin: {hook_impl.plugin_name}, Hook: {hook_name}\n" + f"{type(e).__name__}: {e}\n" + f"For more information see https://pluggy.readthedocs.io/en/stable/api_reference.html#pluggy.PluggyTeardownRaisedWarning" + ) + warnings.warn(PluggyTeardownRaisedWarning(msg), stacklevel=6) + + +def _multicall( + hook_name: str, + hook_impls: Sequence[HookImpl], + caller_kwargs: Mapping[str, object], + firstresult: bool, +) -> object | list[object]: + """Execute a call into multiple python functions/methods and return the + result(s). + + ``caller_kwargs`` comes from HookCaller.__call__(). + """ + __tracebackhide__ = True + results: list[object] = [] + exception = None + teardowns: list[Teardown] = [] + try: # run impl and wrapper setup functions in a loop + for hook_impl in reversed(hook_impls): + try: + args = [caller_kwargs[argname] for argname in hook_impl.argnames] + except KeyError as e: + raise HookCallError( + f"hook call must provide argument {e.args[0]!r}" + ) from e + + if hook_impl.hookwrapper: + function_gen = run_old_style_hookwrapper(hook_impl, hook_name, args) + + next(function_gen) # first yield + teardowns.append(function_gen) + + elif hook_impl.wrapper: + res = hook_impl.function(*args) + # If this cast is not valid, a type error is raised below, + # which is the desired response. + if TYPE_CHECKING: + function_gen = cast(Generator[None, object, object], res) + else: + function_gen = res + try: + next(function_gen) # first yield + except StopIteration: + _raise_wrapfail(function_gen, "did not yield") + teardowns.append(function_gen) + else: + res = hook_impl.function(*args) + if res is not None: + results.append(res) + if firstresult: # halt further impl calls + break + except BaseException as exc: + exception = exc + finally: + if firstresult: # first result hooks return a single value + result = results[0] if results else None + else: + result = results + + # run all wrapper post-yield blocks + for teardown in reversed(teardowns): + try: + if exception is not None: + try: + teardown.throw(exception) + except RuntimeError as re: + # StopIteration from generator causes RuntimeError + # even for coroutine usage - see #544 + if ( + isinstance(exception, StopIteration) + and re.__cause__ is exception + ): + teardown.close() + continue + else: + raise + else: + teardown.send(result) + # Following is unreachable for a well behaved hook wrapper. + # Try to force finalizers otherwise postponed till GC action. + # Note: close() may raise if generator handles GeneratorExit. + teardown.close() + except StopIteration as si: + result = si.value + exception = None + continue + except BaseException as e: + exception = e + continue + _raise_wrapfail(teardown, "has second yield") + + if exception is not None: + raise exception + else: + return result diff --git a/src/pluggy/_hooks.py b/src/pluggy/_hooks.py index 1480308e..b57aae66 100644 --- a/src/pluggy/_hooks.py +++ b/src/pluggy/_hooks.py @@ -1,752 +1,47 @@ """ Internal hook annotation, representation and calling machinery. + +This module re-exports symbols from the role-specific modules for +backward compatibility. """ from __future__ import annotations -from collections.abc import Callable -from collections.abc import Generator -from collections.abc import Mapping -from collections.abc import Sequence -from collections.abc import Set as AbstractSet -import inspect -import sys -import types -from types import ModuleType -from typing import Any -from typing import Final -from typing import final -from typing import overload -from typing import TYPE_CHECKING -from typing import TypeAlias -from typing import TypedDict -from typing import TypeVar -import warnings - -from ._result import Result - - -_T = TypeVar("_T") -_F = TypeVar("_F", bound=Callable[..., object]) - -_Namespace: TypeAlias = ModuleType | type -_Plugin: TypeAlias = object -_HookExec: TypeAlias = Callable[ - [str, Sequence["HookImpl"], Mapping[str, object], bool], - object | list[object], -] -_HookImplFunction: TypeAlias = Callable[..., _T | Generator[None, Result[_T], None]] - - -class HookspecOpts(TypedDict): - """Options for a hook specification.""" - - #: Whether the hook is :ref:`first result only `. - firstresult: bool - #: Whether the hook is :ref:`historic `. - historic: bool - #: Whether the hook :ref:`warns when implemented `. - warn_on_impl: Warning | None - #: Whether the hook warns when :ref:`certain arguments are requested - #: `. - #: - #: .. versionadded:: 1.5 - warn_on_impl_args: Mapping[str, Warning] | None - - -class HookimplOpts(TypedDict): - """Options for a hook implementation.""" - - #: Whether the hook implementation is a :ref:`wrapper `. - wrapper: bool - #: Whether the hook implementation is an :ref:`old-style wrapper - #: `. - hookwrapper: bool - #: Whether validation against a hook specification is :ref:`optional - #: `. - optionalhook: bool - #: Whether to try to order this hook implementation :ref:`first - #: `. - tryfirst: bool - #: Whether to try to order this hook implementation :ref:`last - #: `. - trylast: bool - #: The name of the hook specification to match, see :ref:`specname`. - specname: str | None - - -@final -class HookspecMarker: - """Decorator for marking functions as hook specifications. - - Instantiate it with a project_name to get a decorator. - Calling :meth:`PluginManager.add_hookspecs` later will discover all marked - functions if the :class:`PluginManager` uses the same project name. - """ - - __slots__ = ("project_name",) - - def __init__(self, project_name: str) -> None: - self.project_name: Final = project_name - - @overload - def __call__( - self, - function: _F, - firstresult: bool = False, - historic: bool = False, - warn_on_impl: Warning | None = None, - warn_on_impl_args: Mapping[str, Warning] | None = None, - ) -> _F: ... - - @overload - def __call__( - self, - function: None = ..., - firstresult: bool = ..., - historic: bool = ..., - warn_on_impl: Warning | None = ..., - warn_on_impl_args: Mapping[str, Warning] | None = ..., - ) -> Callable[[_F], _F]: ... - - def __call__( - self, - function: _F | None = None, - firstresult: bool = False, - historic: bool = False, - warn_on_impl: Warning | None = None, - warn_on_impl_args: Mapping[str, Warning] | None = None, - ) -> _F | Callable[[_F], _F]: - """If passed a function, directly sets attributes on the function - which will make it discoverable to :meth:`PluginManager.add_hookspecs`. - - If passed no function, returns a decorator which can be applied to a - function later using the attributes supplied. - - :param firstresult: - If ``True``, the 1:N hook call (N being the number of registered - hook implementation functions) will stop at I<=N when the I'th - function returns a non-``None`` result. See :ref:`firstresult`. - - :param historic: - If ``True``, every call to the hook will be memorized and replayed - on plugins registered after the call was made. See :ref:`historic`. - - :param warn_on_impl: - If given, every implementation of this hook will trigger the given - warning. See :ref:`warn_on_impl`. - - :param warn_on_impl_args: - If given, every implementation of this hook which requests one of - the arguments in the dict will trigger the corresponding warning. - See :ref:`warn_on_impl`. - - .. versionadded:: 1.5 - """ - - def setattr_hookspec_opts(func: _F) -> _F: - if historic and firstresult: - raise ValueError("cannot have a historic firstresult hook") - opts: HookspecOpts = { - "firstresult": firstresult, - "historic": historic, - "warn_on_impl": warn_on_impl, - "warn_on_impl_args": warn_on_impl_args, - } - setattr(func, self.project_name + "_spec", opts) - return func - - if function is not None: - return setattr_hookspec_opts(function) - else: - return setattr_hookspec_opts - - -@final -class HookimplMarker: - """Decorator for marking functions as hook implementations. - - Instantiate it with a ``project_name`` to get a decorator. - Calling :meth:`PluginManager.register` later will discover all marked - functions if the :class:`PluginManager` uses the same project name. - """ - - __slots__ = ("project_name",) - - def __init__(self, project_name: str) -> None: - self.project_name: Final = project_name - - @overload - def __call__( - self, - function: _F, - hookwrapper: bool = ..., - optionalhook: bool = ..., - tryfirst: bool = ..., - trylast: bool = ..., - specname: str | None = ..., - wrapper: bool = ..., - ) -> _F: ... - - @overload - def __call__( - self, - function: None = ..., - hookwrapper: bool = ..., - optionalhook: bool = ..., - tryfirst: bool = ..., - trylast: bool = ..., - specname: str | None = ..., - wrapper: bool = ..., - ) -> Callable[[_F], _F]: ... - - def __call__( - self, - function: _F | None = None, - hookwrapper: bool = False, - optionalhook: bool = False, - tryfirst: bool = False, - trylast: bool = False, - specname: str | None = None, - wrapper: bool = False, - ) -> _F | Callable[[_F], _F]: - """If passed a function, directly sets attributes on the function - which will make it discoverable to :meth:`PluginManager.register`. - - If passed no function, returns a decorator which can be applied to a - function later using the attributes supplied. - - :param optionalhook: - If ``True``, a missing matching hook specification will not result - in an error (by default it is an error if no matching spec is - found). See :ref:`optionalhook`. - - :param tryfirst: - If ``True``, this hook implementation will run as early as possible - in the chain of N hook implementations for a specification. See - :ref:`callorder`. - - :param trylast: - If ``True``, this hook implementation will run as late as possible - in the chain of N hook implementations for a specification. See - :ref:`callorder`. - - :param wrapper: - If ``True`` ("new-style hook wrapper"), the hook implementation - needs to execute exactly one ``yield``. The code before the - ``yield`` is run early before any non-hook-wrapper function is run. - The code after the ``yield`` is run after all non-hook-wrapper - functions have run. The ``yield`` receives the result value of the - inner calls, or raises the exception of inner calls (including - earlier hook wrapper calls). The return value of the function - becomes the return value of the hook, and a raised exception becomes - the exception of the hook. See :ref:`hookwrapper`. - - :param hookwrapper: - If ``True`` ("old-style hook wrapper"), the hook implementation - needs to execute exactly one ``yield``. The code before the - ``yield`` is run early before any non-hook-wrapper function is run. - The code after the ``yield`` is run after all non-hook-wrapper - function have run The ``yield`` receives a :class:`Result` object - representing the exception or result outcome of the inner calls - (including earlier hook wrapper calls). This option is mutually - exclusive with ``wrapper``. See :ref:`old_style_hookwrapper`. - - :param specname: - If provided, the given name will be used instead of the function - name when matching this hook implementation to a hook specification - during registration. See :ref:`specname`. - - .. versionadded:: 1.2.0 - The ``wrapper`` parameter. - """ - - def setattr_hookimpl_opts(func: _F) -> _F: - opts: HookimplOpts = { - "wrapper": wrapper, - "hookwrapper": hookwrapper, - "optionalhook": optionalhook, - "tryfirst": tryfirst, - "trylast": trylast, - "specname": specname, - } - setattr(func, self.project_name + "_impl", opts) - return func - - if function is None: - return setattr_hookimpl_opts - else: - return setattr_hookimpl_opts(function) - - -def normalize_hookimpl_opts(opts: HookimplOpts) -> None: - opts.setdefault("tryfirst", False) - opts.setdefault("trylast", False) - opts.setdefault("wrapper", False) - opts.setdefault("hookwrapper", False) - opts.setdefault("optionalhook", False) - opts.setdefault("specname", None) - - -_PYPY = sys.implementation.name == "pypy" -_IMPLICIT_NAMES = ("self", "cls", "obj") if _PYPY else ("self", "cls") - -# Qualnames whose missing-self deprecation warning is suppressed because -# their upstream code is already fixed but not yet released. -# Remove entries once a release with the fix is available. -_NOSELF_WARN_SUPPRESS: frozenset[str] = frozenset( - { - # pytest-timeout >=2.3.2 has the fix, but is unreleased as of 2026-05. - "TimeoutHooks.pytest_timeout_set_timer", - "TimeoutHooks.pytest_timeout_cancel_timer", - } -) - - -def varnames( - func: object, *, legacy_noself: bool = False -) -> tuple[tuple[str, ...], tuple[str, ...]]: - """Return tuple of positional and keyword parameter names for a callable. - - In case of a class, its ``__init__`` method is considered. - For bound methods, the already-bound first parameter is not included. - For unbound methods with a dotted ``__qualname__``, the first parameter is - stripped only if its name is a known implicit name (``self``, ``cls``). - Keyword-only parameters are not included. - - :param legacy_noself: - If ``True``, support hookspec classes whose methods omit ``self``. - When the function looks like a class method but has no implicit first - parameter, a :class:`DeprecationWarning` is emitted. - """ - is_bound = False - if inspect.isclass(func): - try: - func = func.__init__ - except AttributeError: # pragma: no cover - pypy special case - return (), () - is_bound = True - elif not inspect.isroutine(func): # callable object? - try: - # Not a `callable()` check: the `__call__` attribute itself is - # wanted, so that its signature can be inspected below. - func = getattr(func, "__call__", func) # noqa: B004 - except Exception: # pragma: no cover - pypy special case - return (), () - - # Track bound methods before unwrapping, since __func__ loses that info. - if inspect.ismethod(func): - is_bound = True - func = inspect.unwrap(func) # type: ignore[arg-type] - if inspect.ismethod(func): - is_bound = True - func = func.__func__ - - try: - code: types.CodeType = func.__code__ # type: ignore[attr-defined] - defaults: tuple[object, ...] | None = func.__defaults__ # type: ignore[attr-defined] - qualname: str = func.__qualname__ # type: ignore[attr-defined] - except AttributeError: # pragma: no cover - return (), () - - # Get positional argument names (positional-only + positional-or-keyword) - args: tuple[str, ...] = code.co_varnames[: code.co_argcount] - - # Determine which args have defaults - kwargs: tuple[str, ...] - if defaults: - index = -len(defaults) - args, kwargs = args[:index], args[index:] - else: - kwargs = () - - # Strip implicit instance/class arg. - # Check if this looks like a method defined in a class by examining the - # qualname after the last "." segment (if any). A remaining dot - # means it's a class method (e.g. "MyClass.method" or - # "func..MyClass.method"), not just a nested function. - _tail = qualname.rsplit(".", maxsplit=1)[-1] - _is_class_method = "." in _tail - if args: - if is_bound or (_is_class_method and args[0] in _IMPLICIT_NAMES): - args = args[1:] - elif _is_class_method and legacy_noself and _tail not in _NOSELF_WARN_SUPPRESS: - warnings.warn( - f"{qualname} is a method but its first parameter" - f" {args[0]!r} is not 'self'." - f" Add 'self' as the first parameter or use @staticmethod." - f" This will become an error in a future version of pluggy.", - DeprecationWarning, - stacklevel=2, - ) - - return args, kwargs - - -@final -class HookRelay: - """Hook holder object for performing 1:N hook calls where N is the number - of registered plugins.""" - - __slots__ = ("__dict__",) - - def __init__(self) -> None: - """:meta private:""" - - if TYPE_CHECKING: - - def __getattr__(self, name: str) -> HookCaller: ... - - -# Historical name (pluggy<=1.2), kept for backward compatibility. -_HookRelay = HookRelay - - -_CallHistory: TypeAlias = list[ - tuple[Mapping[str, object], Callable[[Any], None] | None] +from ._caller import _HookCaller +from ._caller import _HookExec +from ._caller import _HookRelay +from ._caller import _SubsetHookCaller +from ._caller import HookCaller +from ._caller import HookRelay +from ._config import HookimplOpts +from ._config import HookspecOpts +from ._config import normalize_hookimpl_opts +from ._decorators import _Namespace +from ._decorators import HookimplMarker +from ._decorators import HookSpec +from ._decorators import HookspecMarker +from ._decorators import varnames +from ._impl import _HookImplFunction +from ._impl import _Plugin +from ._impl import HookImpl + + +__all__ = [ + "HookCaller", + "HookImpl", + "HookRelay", + "HookSpec", + "HookimplMarker", + "HookimplOpts", + "HookspecMarker", + "HookspecOpts", + "_HookCaller", + "_HookExec", + "_HookImplFunction", + "_HookRelay", + "_Namespace", + "_Plugin", + "_SubsetHookCaller", + "normalize_hookimpl_opts", + "varnames", ] - - -class HookCaller: - """A caller of all registered implementations of a hook specification.""" - - __slots__ = ( - "_call_history", - "_hookexec", - "_hookimpls", - "name", - "spec", - ) - - def __init__( - self, - name: str, - hook_execute: _HookExec, - specmodule_or_class: _Namespace | None = None, - spec_opts: HookspecOpts | None = None, - ) -> None: - """:meta private:""" - #: Name of the hook getting called. - self.name: Final = name - self._hookexec: Final = hook_execute - # The hookimpls list. The caller iterates it *in reverse*. Format: - # 1. trylast nonwrappers - # 2. nonwrappers - # 3. tryfirst nonwrappers - # 4. trylast wrappers - # 5. wrappers - # 6. tryfirst wrappers - self._hookimpls: Final[list[HookImpl]] = [] - self._call_history: _CallHistory | None = None - # TODO: Document, or make private. - self.spec: HookSpec | None = None - if specmodule_or_class is not None: - assert spec_opts is not None - self.set_specification(specmodule_or_class, spec_opts) - - # TODO: Document, or make private. - def has_spec(self) -> bool: - return self.spec is not None - - # TODO: Document, or make private. - def set_specification( - self, - specmodule_or_class: _Namespace, - spec_opts: HookspecOpts, - ) -> None: - if self.spec is not None: - raise ValueError( - f"Hook {self.spec.name!r} is already registered " - f"within namespace {self.spec.namespace}" - ) - self.spec = HookSpec(specmodule_or_class, self.name, spec_opts) - if spec_opts.get("historic"): - self._call_history = [] - - def is_historic(self) -> bool: - """Whether this caller is :ref:`historic `.""" - return self._call_history is not None - - def _remove_plugin(self, plugin: _Plugin) -> None: - """Remove all hook implementations registered by the given plugin.""" - remaining = [impl for impl in self._hookimpls if impl.plugin != plugin] - if len(remaining) == len(self._hookimpls): - raise ValueError(f"plugin {plugin!r} not found") - self._hookimpls[:] = remaining - - def get_hookimpls(self) -> list[HookImpl]: - """Get all registered hook implementations for this hook.""" - return self._hookimpls.copy() - - def _add_hookimpl(self, hookimpl: HookImpl) -> None: - """Add an implementation to the callback chain.""" - for i, method in enumerate(self._hookimpls): - if method.hookwrapper or method.wrapper: - splitpoint = i - break - else: - splitpoint = len(self._hookimpls) - if hookimpl.hookwrapper or hookimpl.wrapper: - start, end = splitpoint, len(self._hookimpls) - else: - start, end = 0, splitpoint - - if hookimpl.trylast: - self._hookimpls.insert(start, hookimpl) - elif hookimpl.tryfirst: - self._hookimpls.insert(end, hookimpl) - else: - # find last non-tryfirst method - i = end - 1 - while i >= start and self._hookimpls[i].tryfirst: - i -= 1 - self._hookimpls.insert(i + 1, hookimpl) - - def __repr__(self) -> str: - return f"" - - def _verify_all_args_are_provided(self, kwargs: Mapping[str, object]) -> None: - # This is written to avoid expensive operations when not needed. - if self.spec: - for argname in self.spec.argnames: - if argname not in kwargs: - notincall = ", ".join( - repr(argname) - for argname in self.spec.argnames - # Avoid self.spec.argnames - kwargs.keys() - # it doesn't preserve order. - if argname not in kwargs - ) - warnings.warn( - f"Argument(s) {notincall} which are declared in the hookspec " - "cannot be found in this hook call", - # 3, not 2: the warning is raised in this helper, which - # is called by __call__/call_historic/call_extra, which - # are called by the code making the hook call. - stacklevel=3, - ) - break - - def __call__(self, **kwargs: object) -> Any: - """Call the hook. - - Only accepts keyword arguments, which should match the hook - specification. - - Returns the result(s) of calling all registered plugins, see - :ref:`calling`. - """ - assert not self.is_historic(), ( - "Cannot directly call a historic hook - use call_historic instead." - ) - self._verify_all_args_are_provided(kwargs) - firstresult = self.spec.opts.get("firstresult", False) if self.spec else False - # Copy because plugins may register other plugins during iteration (#438). - return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) - - def call_historic( - self, - result_callback: Callable[[Any], None] | None = None, - kwargs: Mapping[str, object] | None = None, - ) -> None: - """Call the hook with given ``kwargs`` for all registered plugins and - for all plugins which will be registered afterwards, see - :ref:`historic`. - - :param result_callback: - If provided, will be called for each non-``None`` result obtained - from a hook implementation. - """ - assert self._call_history is not None - kwargs = kwargs or {} - self._verify_all_args_are_provided(kwargs) - self._call_history.append((kwargs, result_callback)) - # Historizing hooks don't return results. - # Remember firstresult isn't compatible with historic. - # Copy because plugins may register other plugins during iteration (#438). - res = self._hookexec(self.name, self._hookimpls.copy(), kwargs, False) - if result_callback is None: - return - if isinstance(res, list): - for x in res: - result_callback(x) - - def call_extra( - self, methods: Sequence[Callable[..., object]], kwargs: Mapping[str, object] - ) -> Any: - """Call the hook with some additional temporarily participating - methods using the specified ``kwargs`` as call parameters, see - :ref:`call_extra`.""" - assert not self.is_historic(), ( - "Cannot directly call a historic hook - use call_historic instead." - ) - self._verify_all_args_are_provided(kwargs) - opts: HookimplOpts = { - "wrapper": False, - "hookwrapper": False, - "optionalhook": False, - "trylast": False, - "tryfirst": False, - "specname": None, - } - hookimpls = self._hookimpls.copy() - for method in methods: - hookimpl = HookImpl(None, "", method, opts) - # Find last non-tryfirst nonwrapper method. - i = len(hookimpls) - 1 - while i >= 0 and ( - # Skip wrappers. - (hookimpls[i].hookwrapper or hookimpls[i].wrapper) - # Skip tryfirst nonwrappers. - or hookimpls[i].tryfirst - ): - i -= 1 - hookimpls.insert(i + 1, hookimpl) - firstresult = self.spec.opts.get("firstresult", False) if self.spec else False - return self._hookexec(self.name, hookimpls, kwargs, firstresult) - - def _maybe_apply_history(self, method: HookImpl) -> None: - """Apply call history to a new hookimpl if it is marked as historic.""" - if self.is_historic(): - assert self._call_history is not None - for kwargs, result_callback in self._call_history: - res = self._hookexec(self.name, [method], kwargs, False) - if res and result_callback is not None: - # XXX: remember firstresult isn't compat with historic - assert isinstance(res, list) - result_callback(res[0]) - - -# Historical name (pluggy<=1.2), kept for backward compatibility. -_HookCaller = HookCaller - - -class _SubsetHookCaller(HookCaller): - """A proxy to another HookCaller which manages calls to all registered - plugins except the ones from remove_plugins.""" - - # This class is unusual: in inhertits from `HookCaller` so all of - # the *code* runs in the class, but it delegates all underlying *data* - # to the original HookCaller. - # `subset_hook_caller` used to be implemented by creating a full-fledged - # HookCaller, copying all hookimpls from the original. This had problems - # with memory leaks (#346) and historic calls (#347), which make a proxy - # approach better. - # An alternative implementation is to use a `_getattr__`/`__getattribute__` - # proxy, however that adds more overhead and is more tricky to implement. - - __slots__ = ( - "_orig", - "_remove_plugins", - ) - - def __init__(self, orig: HookCaller, remove_plugins: AbstractSet[_Plugin]) -> None: - self._orig = orig - self._remove_plugins = remove_plugins - self.name = orig.name # type: ignore[misc] - self._hookexec = orig._hookexec # type: ignore[misc] - - @property # type: ignore[misc] - def _hookimpls(self) -> list[HookImpl]: - return [ - impl - for impl in self._orig._hookimpls - if impl.plugin not in self._remove_plugins - ] - - @property - def spec(self) -> HookSpec | None: # type: ignore[override] - return self._orig.spec - - @property - def _call_history(self) -> _CallHistory | None: # type: ignore[override] - return self._orig._call_history - - def __repr__(self) -> str: - return f"<_SubsetHookCaller {self.name!r}>" - - -@final -class HookImpl: - """A hook implementation in a :class:`HookCaller`.""" - - __slots__ = ( - "argnames", - "function", - "hookwrapper", - "kwargnames", - "optionalhook", - "opts", - "plugin", - "plugin_name", - "tryfirst", - "trylast", - "wrapper", - ) - - def __init__( - self, - plugin: _Plugin, - plugin_name: str, - function: _HookImplFunction[object], - hook_impl_opts: HookimplOpts, - ) -> None: - """:meta private:""" - #: The hook implementation function. - self.function: Final = function - argnames, kwargnames = varnames(self.function) - #: The positional parameter names of ``function```. - self.argnames: Final = argnames - #: The keyword parameter names of ``function```. - self.kwargnames: Final = kwargnames - #: The plugin which defined this hook implementation. - self.plugin: Final = plugin - #: The :class:`HookimplOpts` used to configure this hook implementation. - self.opts: Final = hook_impl_opts - #: The name of the plugin which defined this hook implementation. - self.plugin_name: Final = plugin_name - #: Whether the hook implementation is a :ref:`wrapper `. - self.wrapper: Final = hook_impl_opts["wrapper"] - #: Whether the hook implementation is an :ref:`old-style wrapper - #: `. - self.hookwrapper: Final = hook_impl_opts["hookwrapper"] - #: Whether validation against a hook specification is :ref:`optional - #: `. - self.optionalhook: Final = hook_impl_opts["optionalhook"] - #: Whether to try to order this hook implementation :ref:`first - #: `. - self.tryfirst: Final = hook_impl_opts["tryfirst"] - #: Whether to try to order this hook implementation :ref:`last - #: `. - self.trylast: Final = hook_impl_opts["trylast"] - - def __repr__(self) -> str: - return f"" - - -@final -class HookSpec: - __slots__ = ( - "argnames", - "function", - "kwargnames", - "name", - "namespace", - "opts", - "warn_on_impl", - "warn_on_impl_args", - ) - - def __init__(self, namespace: _Namespace, name: str, opts: HookspecOpts) -> None: - self.namespace = namespace - self.name = name - self.function: Callable[..., object] = getattr(namespace, name) - legacy_noself = inspect.isclass(namespace) and not isinstance( - inspect.getattr_static(namespace, name), staticmethod - ) - self.argnames, self.kwargnames = varnames( - self.function, legacy_noself=legacy_noself - ) - self.opts = opts - self.warn_on_impl = opts.get("warn_on_impl") - self.warn_on_impl_args = opts.get("warn_on_impl_args") diff --git a/src/pluggy/_impl.py b/src/pluggy/_impl.py new file mode 100644 index 00000000..4f82ebe5 --- /dev/null +++ b/src/pluggy/_impl.py @@ -0,0 +1,80 @@ +""" +Hook implementation representation. +""" + +from __future__ import annotations + +from collections.abc import Callable +from collections.abc import Generator +from typing import Final +from typing import final +from typing import TypeAlias +from typing import TypeVar + +from ._config import HookimplOpts +from ._decorators import varnames +from ._result import Result + + +_T = TypeVar("_T") + +_Plugin: TypeAlias = object +_HookImplFunction: TypeAlias = Callable[..., _T | Generator[None, Result[_T], None]] + + +@final +class HookImpl: + """A hook implementation in a :class:`HookCaller`.""" + + __slots__ = ( + "argnames", + "function", + "hookwrapper", + "kwargnames", + "optionalhook", + "opts", + "plugin", + "plugin_name", + "tryfirst", + "trylast", + "wrapper", + ) + + def __init__( + self, + plugin: _Plugin, + plugin_name: str, + function: _HookImplFunction[object], + hook_impl_opts: HookimplOpts, + ) -> None: + """:meta private:""" + #: The hook implementation function. + self.function: Final = function + argnames, kwargnames = varnames(self.function) + #: The positional parameter names of ``function```. + self.argnames: Final = argnames + #: The keyword parameter names of ``function```. + self.kwargnames: Final = kwargnames + #: The plugin which defined this hook implementation. + self.plugin: Final = plugin + #: The :class:`HookimplOpts` used to configure this hook implementation. + self.opts: Final = hook_impl_opts + #: The name of the plugin which defined this hook implementation. + self.plugin_name: Final = plugin_name + #: Whether the hook implementation is a :ref:`wrapper `. + self.wrapper: Final = hook_impl_opts["wrapper"] + #: Whether the hook implementation is an :ref:`old-style wrapper + #: `. + self.hookwrapper: Final = hook_impl_opts["hookwrapper"] + #: Whether validation against a hook specification is :ref:`optional + #: `. + self.optionalhook: Final = hook_impl_opts["optionalhook"] + #: Whether to try to order this hook implementation :ref:`first + #: `. + self.tryfirst: Final = hook_impl_opts["tryfirst"] + #: Whether to try to order this hook implementation :ref:`last + #: `. + self.trylast: Final = hook_impl_opts["trylast"] + + def __repr__(self) -> str: + return f"" From a48959a6c8b7444f2517e771abb0999575ffac74 Mon Sep 17 00:00:00 2001 From: Ronny Pfannschmidt Date: Wed, 22 Jul 2026 14:40:06 +0200 Subject: [PATCH 2/5] feat(config): replace TypedDict options with Hook*Configuration Markers attach HookspecConfiguration/HookimplConfiguration objects. Registration discovers those privately; parse_hookimpl_opts and parse_hookspec_opts remain a deprecated pytest concession that returns legacy dicts and is only called when a subclass overrides them and no modern configuration attribute was found. Co-authored-by: Cursor AI Co-authored-by: Cursor Grok 4.5 --- changelog/704.removal.rst | 8 + docs/api_reference.rst | 6 +- docs/index.rst | 9 +- src/pluggy/__init__.py | 8 +- src/pluggy/_caller.py | 23 +-- src/pluggy/_config.py | 207 +++++++++++++++++++------ src/pluggy/_decorators.py | 46 +++--- src/pluggy/_hooks.py | 10 +- src/pluggy/_impl.py | 17 ++- src/pluggy/_manager.py | 168 +++++++++++++------- src/pluggy/_pytest_compat.py | 55 +++++++ testing/test_configuration.py | 278 ++++++++++++++++++++++++++++++++++ testing/test_details.py | 8 +- testing/test_hookcaller.py | 8 +- 14 files changed, 685 insertions(+), 166 deletions(-) create mode 100644 changelog/704.removal.rst create mode 100644 src/pluggy/_pytest_compat.py create mode 100644 testing/test_configuration.py diff --git a/changelog/704.removal.rst b/changelog/704.removal.rst new file mode 100644 index 00000000..4d5eef43 --- /dev/null +++ b/changelog/704.removal.rst @@ -0,0 +1,8 @@ +Hook options are now :class:`pluggy.HookspecConfiguration` / +:class:`pluggy.HookimplConfiguration` objects (markers attach these instead of +dicts). ``PluginManager.parse_hookimpl_opts`` / +``parse_hookspec_opts`` remain as a deprecated pytest/support concession that +returns legacy dicts and are only invoked during registration when a subclass +overrides them and no modern configuration attribute was found. +``HookspecOpts`` / ``HookimplOpts`` TypedDicts remain importable for +pytest/typing compatibility. diff --git a/docs/api_reference.rst b/docs/api_reference.rst index b14d725d..7d19a4a6 100644 --- a/docs/api_reference.rst +++ b/docs/api_reference.rst @@ -40,12 +40,10 @@ API Reference .. autoclass:: pluggy.HookImpl() :members: -.. autoclass:: pluggy.HookspecOpts() - :show-inheritance: +.. autoclass:: pluggy.HookspecConfiguration() :members: -.. autoclass:: pluggy.HookimplOpts() - :show-inheritance: +.. autoclass:: pluggy.HookimplConfiguration() :members: diff --git a/docs/index.rst b/docs/index.rst index b56278ed..1f1292ae 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -767,10 +767,13 @@ and particular plugins in it: Parsing mark options ^^^^^^^^^^^^^^^^^^^^ -You can retrieve the *options* applied to a particular -*hookspec* or *hookimpl* as per :ref:`marking_hooks` using the +Markers attach :class:`~pluggy.HookspecConfiguration` / +:class:`~pluggy.HookimplConfiguration` objects to functions. The :py:meth:`~pluggy.PluginManager.parse_hookspec_opts()` and -:py:meth:`~pluggy.PluginManager.parse_hookimpl_opts()` respectively. +:py:meth:`~pluggy.PluginManager.parse_hookimpl_opts()` methods remain as a +**deprecated** pytest/support concession that returns legacy dict-shaped +options; registration only calls them when a subclass overrides them and no +modern configuration attribute was found. .. _calling: diff --git a/src/pluggy/__init__.py b/src/pluggy/__init__.py index 32c7eae5..83064d90 100644 --- a/src/pluggy/__init__.py +++ b/src/pluggy/__init__.py @@ -3,8 +3,10 @@ "HookCaller", "HookImpl", "HookRelay", + "HookimplConfiguration", "HookimplMarker", "HookimplOpts", + "HookspecConfiguration", "HookspecMarker", "HookspecOpts", "PluggyTeardownRaisedWarning", @@ -14,15 +16,17 @@ "Result", "__version__", ] +from ._config import HookimplConfiguration +from ._config import HookspecConfiguration from ._hooks import HookCaller from ._hooks import HookImpl from ._hooks import HookimplMarker -from ._hooks import HookimplOpts from ._hooks import HookRelay from ._hooks import HookspecMarker -from ._hooks import HookspecOpts from ._manager import PluginManager from ._manager import PluginValidationError +from ._pytest_compat import HookimplOpts +from ._pytest_compat import HookspecOpts from ._result import HookCallError from ._result import Result from ._warnings import PluggyTeardownRaisedWarning diff --git a/src/pluggy/_caller.py b/src/pluggy/_caller.py index ea95b800..15ce95d7 100644 --- a/src/pluggy/_caller.py +++ b/src/pluggy/_caller.py @@ -15,8 +15,8 @@ from typing import TypeAlias import warnings -from ._config import HookimplOpts -from ._config import HookspecOpts +from ._config import HookimplConfiguration +from ._config import HookspecConfiguration from ._decorators import _Namespace from ._decorators import HookSpec from ._impl import _Plugin @@ -69,7 +69,7 @@ def __init__( name: str, hook_execute: _HookExec, specmodule_or_class: _Namespace | None = None, - spec_opts: HookspecOpts | None = None, + spec_opts: HookspecConfiguration | None = None, ) -> None: """:meta private:""" #: Name of the hook getting called. @@ -98,7 +98,7 @@ def has_spec(self) -> bool: def set_specification( self, specmodule_or_class: _Namespace, - spec_opts: HookspecOpts, + spec_opts: HookspecConfiguration, ) -> None: if self.spec is not None: raise ValueError( @@ -106,7 +106,7 @@ def set_specification( f"within namespace {self.spec.namespace}" ) self.spec = HookSpec(specmodule_or_class, self.name, spec_opts) - if spec_opts.get("historic"): + if spec_opts.historic: self._call_history = [] def is_historic(self) -> bool: @@ -186,7 +186,7 @@ def __call__(self, **kwargs: object) -> Any: "Cannot directly call a historic hook - use call_historic instead." ) self._verify_all_args_are_provided(kwargs) - firstresult = self.spec.opts.get("firstresult", False) if self.spec else False + firstresult = self.spec.opts.firstresult if self.spec else False # Copy because plugins may register other plugins during iteration (#438). return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) @@ -227,14 +227,7 @@ def call_extra( "Cannot directly call a historic hook - use call_historic instead." ) self._verify_all_args_are_provided(kwargs) - opts: HookimplOpts = { - "wrapper": False, - "hookwrapper": False, - "optionalhook": False, - "trylast": False, - "tryfirst": False, - "specname": None, - } + opts = HookimplConfiguration() hookimpls = self._hookimpls.copy() for method in methods: hookimpl = HookImpl(None, "", method, opts) @@ -248,7 +241,7 @@ def call_extra( ): i -= 1 hookimpls.insert(i + 1, hookimpl) - firstresult = self.spec.opts.get("firstresult", False) if self.spec else False + firstresult = self.spec.opts.firstresult if self.spec else False return self._hookexec(self.name, hookimpls, kwargs, firstresult) def _maybe_apply_history(self, method: HookImpl) -> None: diff --git a/src/pluggy/_config.py b/src/pluggy/_config.py index 576a7794..48ead414 100644 --- a/src/pluggy/_config.py +++ b/src/pluggy/_config.py @@ -5,50 +5,163 @@ from __future__ import annotations from collections.abc import Mapping -from typing import TypedDict - - -class HookspecOpts(TypedDict): - """Options for a hook specification.""" - - #: Whether the hook is :ref:`first result only `. - firstresult: bool - #: Whether the hook is :ref:`historic `. - historic: bool - #: Whether the hook :ref:`warns when implemented `. - warn_on_impl: Warning | None - #: Whether the hook warns when :ref:`certain arguments are requested - #: `. - #: - #: .. versionadded:: 1.5 - warn_on_impl_args: Mapping[str, Warning] | None - - -class HookimplOpts(TypedDict): - """Options for a hook implementation.""" - - #: Whether the hook implementation is a :ref:`wrapper `. - wrapper: bool - #: Whether the hook implementation is an :ref:`old-style wrapper - #: `. - hookwrapper: bool - #: Whether validation against a hook specification is :ref:`optional - #: `. - optionalhook: bool - #: Whether to try to order this hook implementation :ref:`first - #: `. - tryfirst: bool - #: Whether to try to order this hook implementation :ref:`last - #: `. - trylast: bool - #: The name of the hook specification to match, see :ref:`specname`. - specname: str | None - - -def normalize_hookimpl_opts(opts: HookimplOpts) -> None: - opts.setdefault("tryfirst", False) - opts.setdefault("trylast", False) - opts.setdefault("wrapper", False) - opts.setdefault("hookwrapper", False) - opts.setdefault("optionalhook", False) - opts.setdefault("specname", None) +from typing import Any +from typing import Final +from typing import final + + +@final +class HookspecConfiguration: + """Configuration for a hook specification.""" + + __slots__ = ( + "firstresult", + "historic", + "warn_on_impl", + "warn_on_impl_args", + ) + firstresult: Final[bool] + historic: Final[bool] + warn_on_impl: Final[Warning | None] + warn_on_impl_args: Final[Mapping[str, Warning] | None] + + def __init__( + self, + firstresult: bool = False, + historic: bool = False, + warn_on_impl: Warning | None = None, + warn_on_impl_args: Mapping[str, Warning] | None = None, + ) -> None: + if historic and firstresult: + raise ValueError("cannot have a historic firstresult hook") + #: Whether the hook is :ref:`first result only `. + self.firstresult = firstresult + #: Whether the hook is :ref:`historic `. + self.historic = historic + #: Whether the hook :ref:`warns when implemented `. + self.warn_on_impl = warn_on_impl + #: Whether the hook warns when :ref:`certain arguments are requested + #: `. + self.warn_on_impl_args = warn_on_impl_args + + def __repr__(self) -> str: + attrs = [ + f"{slot}={getattr(self, slot)!r}" + for slot in self.__slots__ + if getattr(self, slot) + ] + return f"HookspecConfiguration({', '.join(attrs)})" + + +@final +class HookimplConfiguration: + """Configuration for a hook implementation.""" + + __slots__ = ( + "hookwrapper", + "optionalhook", + "specname", + "tryfirst", + "trylast", + "wrapper", + ) + wrapper: Final[bool] + hookwrapper: Final[bool] + optionalhook: Final[bool] + tryfirst: Final[bool] + trylast: Final[bool] + specname: Final[str | None] + + def __init__( + self, + wrapper: bool = False, + hookwrapper: bool = False, + optionalhook: bool = False, + tryfirst: bool = False, + trylast: bool = False, + specname: str | None = None, + ) -> None: + #: Whether the hook implementation is a :ref:`wrapper `. + self.wrapper = wrapper + #: Whether the hook implementation is an :ref:`old-style wrapper + #: `. + self.hookwrapper = hookwrapper + #: Whether validation against a hook specification is :ref:`optional + #: `. + self.optionalhook = optionalhook + #: Whether to try to order this hook implementation :ref:`first + #: `. + self.tryfirst = tryfirst + #: Whether to try to order this hook implementation :ref:`last + #: `. + self.trylast = trylast + #: The name of the hook specification to match, see :ref:`specname`. + self.specname = specname + + def __repr__(self) -> str: + attrs = [ + f"{slot}={getattr(self, slot)!r}" + for slot in self.__slots__ + if getattr(self, slot) + ] + return f"HookimplConfiguration({', '.join(attrs)})" + + +def hookspec_config_from_mapping( + opts: Mapping[str, Any], +) -> HookspecConfiguration: + """Build a :class:`HookspecConfiguration` from a mapping. + + Intended for pytest/support migration only — not the public options API. + Prefer constructing :class:`HookspecConfiguration` directly. + """ + return HookspecConfiguration( + firstresult=bool(opts.get("firstresult", False)), + historic=bool(opts.get("historic", False)), + warn_on_impl=opts.get("warn_on_impl"), + warn_on_impl_args=opts.get("warn_on_impl_args"), + ) + + +def hookimpl_config_from_mapping( + opts: Mapping[str, Any], +) -> HookimplConfiguration: + """Build a :class:`HookimplConfiguration` from a mapping. + + Intended for pytest/support migration only — not the public options API. + Prefer constructing :class:`HookimplConfiguration` directly. + """ + return HookimplConfiguration( + wrapper=bool(opts.get("wrapper", False)), + hookwrapper=bool(opts.get("hookwrapper", False)), + optionalhook=bool(opts.get("optionalhook", False)), + tryfirst=bool(opts.get("tryfirst", False)), + trylast=bool(opts.get("trylast", False)), + specname=opts.get("specname"), + ) + + +def hookspec_config_to_mapping( + config: HookspecConfiguration, +) -> dict[str, Any]: + """Serialize configuration to a legacy mapping (pytest/support only).""" + return { + "firstresult": config.firstresult, + "historic": config.historic, + "warn_on_impl": config.warn_on_impl, + "warn_on_impl_args": config.warn_on_impl_args, + } + + +def hookimpl_config_to_mapping( + config: HookimplConfiguration, +) -> dict[str, Any]: + """Serialize configuration to a legacy mapping (pytest/support only).""" + return { + "wrapper": config.wrapper, + "hookwrapper": config.hookwrapper, + "optionalhook": config.optionalhook, + "tryfirst": config.tryfirst, + "trylast": config.trylast, + "specname": config.specname, + } diff --git a/src/pluggy/_decorators.py b/src/pluggy/_decorators.py index 98f1409e..713c978e 100644 --- a/src/pluggy/_decorators.py +++ b/src/pluggy/_decorators.py @@ -17,8 +17,8 @@ from typing import TypeVar import warnings -from ._config import HookimplOpts -from ._config import HookspecOpts +from ._config import HookimplConfiguration +from ._config import HookspecConfiguration _F = TypeVar("_F", bound=Callable[..., object]) @@ -96,15 +96,13 @@ def __call__( """ def setattr_hookspec_opts(func: _F) -> _F: - if historic and firstresult: - raise ValueError("cannot have a historic firstresult hook") - opts: HookspecOpts = { - "firstresult": firstresult, - "historic": historic, - "warn_on_impl": warn_on_impl, - "warn_on_impl_args": warn_on_impl_args, - } - setattr(func, self.project_name + "_spec", opts) + config = HookspecConfiguration( + firstresult=firstresult, + historic=historic, + warn_on_impl=warn_on_impl, + warn_on_impl_args=warn_on_impl_args, + ) + setattr(func, self.project_name + "_spec", config) return func if function is not None: @@ -213,15 +211,15 @@ def __call__( """ def setattr_hookimpl_opts(func: _F) -> _F: - opts: HookimplOpts = { - "wrapper": wrapper, - "hookwrapper": hookwrapper, - "optionalhook": optionalhook, - "tryfirst": tryfirst, - "trylast": trylast, - "specname": specname, - } - setattr(func, self.project_name + "_impl", opts) + config = HookimplConfiguration( + wrapper=wrapper, + hookwrapper=hookwrapper, + optionalhook=optionalhook, + tryfirst=tryfirst, + trylast=trylast, + specname=specname, + ) + setattr(func, self.project_name + "_impl", config) return func if function is None: @@ -338,7 +336,9 @@ class HookSpec: "warn_on_impl_args", ) - def __init__(self, namespace: _Namespace, name: str, opts: HookspecOpts) -> None: + def __init__( + self, namespace: _Namespace, name: str, opts: HookspecConfiguration + ) -> None: self.namespace = namespace self.name = name self.function: Callable[..., object] = getattr(namespace, name) @@ -349,5 +349,5 @@ def __init__(self, namespace: _Namespace, name: str, opts: HookspecOpts) -> None self.function, legacy_noself=legacy_noself ) self.opts = opts - self.warn_on_impl = opts.get("warn_on_impl") - self.warn_on_impl_args = opts.get("warn_on_impl_args") + self.warn_on_impl = opts.warn_on_impl + self.warn_on_impl_args = opts.warn_on_impl_args diff --git a/src/pluggy/_hooks.py b/src/pluggy/_hooks.py index b57aae66..55197772 100644 --- a/src/pluggy/_hooks.py +++ b/src/pluggy/_hooks.py @@ -13,9 +13,8 @@ from ._caller import _SubsetHookCaller from ._caller import HookCaller from ._caller import HookRelay -from ._config import HookimplOpts -from ._config import HookspecOpts -from ._config import normalize_hookimpl_opts +from ._config import HookimplConfiguration +from ._config import HookspecConfiguration from ._decorators import _Namespace from ._decorators import HookimplMarker from ._decorators import HookSpec @@ -31,10 +30,10 @@ "HookImpl", "HookRelay", "HookSpec", + "HookimplConfiguration", "HookimplMarker", - "HookimplOpts", + "HookspecConfiguration", "HookspecMarker", - "HookspecOpts", "_HookCaller", "_HookExec", "_HookImplFunction", @@ -42,6 +41,5 @@ "_Namespace", "_Plugin", "_SubsetHookCaller", - "normalize_hookimpl_opts", "varnames", ] diff --git a/src/pluggy/_impl.py b/src/pluggy/_impl.py index 4f82ebe5..5a2043b6 100644 --- a/src/pluggy/_impl.py +++ b/src/pluggy/_impl.py @@ -11,7 +11,7 @@ from typing import TypeAlias from typing import TypeVar -from ._config import HookimplOpts +from ._config import HookimplConfiguration from ._decorators import varnames from ._result import Result @@ -45,7 +45,7 @@ def __init__( plugin: _Plugin, plugin_name: str, function: _HookImplFunction[object], - hook_impl_opts: HookimplOpts, + hook_impl_opts: HookimplConfiguration, ) -> None: """:meta private:""" #: The hook implementation function. @@ -57,24 +57,25 @@ def __init__( self.kwargnames: Final = kwargnames #: The plugin which defined this hook implementation. self.plugin: Final = plugin - #: The :class:`HookimplOpts` used to configure this hook implementation. + #: The :class:`HookimplConfiguration` used to configure this hook + #: implementation. self.opts: Final = hook_impl_opts #: The name of the plugin which defined this hook implementation. self.plugin_name: Final = plugin_name #: Whether the hook implementation is a :ref:`wrapper `. - self.wrapper: Final = hook_impl_opts["wrapper"] + self.wrapper: Final = hook_impl_opts.wrapper #: Whether the hook implementation is an :ref:`old-style wrapper #: `. - self.hookwrapper: Final = hook_impl_opts["hookwrapper"] + self.hookwrapper: Final = hook_impl_opts.hookwrapper #: Whether validation against a hook specification is :ref:`optional #: `. - self.optionalhook: Final = hook_impl_opts["optionalhook"] + self.optionalhook: Final = hook_impl_opts.optionalhook #: Whether to try to order this hook implementation :ref:`first #: `. - self.tryfirst: Final = hook_impl_opts["tryfirst"] + self.tryfirst: Final = hook_impl_opts.tryfirst #: Whether to try to order this hook implementation :ref:`last #: `. - self.trylast: Final = hook_impl_opts["trylast"] + self.trylast: Final = hook_impl_opts.trylast def __repr__(self) -> str: return f"" diff --git a/src/pluggy/_manager.py b/src/pluggy/_manager.py index 06923c20..506342d6 100644 --- a/src/pluggy/_manager.py +++ b/src/pluggy/_manager.py @@ -15,16 +15,21 @@ from . import _tracing from ._callers import _multicall +from ._config import hookimpl_config_from_mapping +from ._config import hookimpl_config_to_mapping +from ._config import HookimplConfiguration +from ._config import hookspec_config_from_mapping +from ._config import hookspec_config_to_mapping +from ._config import HookspecConfiguration from ._hooks import _HookImplFunction from ._hooks import _Namespace from ._hooks import _Plugin from ._hooks import _SubsetHookCaller from ._hooks import HookCaller from ._hooks import HookImpl -from ._hooks import HookimplOpts from ._hooks import HookRelay -from ._hooks import HookspecOpts -from ._hooks import normalize_hookimpl_opts +from ._pytest_compat import HookimplOpts +from ._pytest_compat import HookspecOpts from ._result import Result @@ -113,16 +118,19 @@ def _static_hook_attr( return None -def _get_marker_opts(holder: object, attrname: str) -> dict[str, Any] | None: - """Read marker options from ``holder``, falling back to ``__func__``.""" - opts = getattr(holder, attrname, None) - if opts is not None: - return opts if isinstance(opts, dict) else None - func = getattr(holder, "__func__", None) +def _get_marker_attr(holder: object, attrname: str) -> object | None: + """Read a marker attribute from ``holder``, falling back to ``__func__``. + + The marker sits on the ``classmethod``/``staticmethod`` wrapper when it was + applied above it, and on the wrapped function when applied below. + """ + marker: object = getattr(holder, attrname, None) + if marker is not None: + return marker + func: object = getattr(holder, "__func__", None) if func is not None: - opts = getattr(func, attrname, None) - if opts is not None: - return opts if isinstance(opts, dict) else None + wrapped: object = getattr(func, attrname, None) + return wrapped return None @@ -218,9 +226,8 @@ def register(self, plugin: _Plugin, name: str | None = None) -> str | None: # register matching hook implementations of the plugin for attr_name in dir(plugin): - hookimpl_opts = self.parse_hookimpl_opts(plugin, attr_name) - if hookimpl_opts is not None: - normalize_hookimpl_opts(hookimpl_opts) + hookimpl_config = self._discover_hookimpl_configuration(plugin, attr_name) + if hookimpl_config is not None: found = _static_hook_attr(plugin, attr_name) # Only reachable when a subclass overrode parse_hookimpl_opts # to claim an attribute pluggy cannot bind. @@ -228,8 +235,8 @@ def register(self, plugin: _Plugin, name: str | None = None) -> str | None: f"{plugin!r}.{attr_name} is not a hookable attribute" ) method: _HookImplFunction[object] = found[1] - hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_opts) - hook_name = hookimpl_opts.get("specname") or attr_name + hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_config) + hook_name = hookimpl_config.specname or attr_name hook: HookCaller | None = getattr(self.hook, hook_name, None) if hook is None: hook = HookCaller(hook_name, self._hookexec) @@ -240,16 +247,10 @@ def register(self, plugin: _Plugin, name: str | None = None) -> str | None: hook._add_hookimpl(hookimpl) return plugin_name - def parse_hookimpl_opts(self, plugin: _Plugin, name: str) -> HookimplOpts | None: - """Try to obtain a hook implementation from an item with the given name - in the given plugin which is being searched for hook impls. - - :returns: - The parsed hookimpl options, or None to skip the given item. - - This method can be overridden by ``PluginManager`` subclasses to - customize how hook implementation are picked up. By default, returns the - options for items decorated with :class:`HookimplMarker`. + def _read_hookimpl_configuration( + self, plugin: _Plugin, name: str + ) -> HookimplConfiguration | None: + """Read a modern :class:`HookimplConfiguration` from a plugin attribute. Discovery uses :func:`inspect.getattr_static` so properties and other descriptors are not executed. Only functions, classmethods, @@ -258,10 +259,46 @@ def parse_hookimpl_opts(self, plugin: _Plugin, name: str) -> HookimplOpts | None found = _static_hook_attr(plugin, name) if found is None: return None - return cast( - HookimplOpts | None, - _get_marker_opts(found[0], self.project_name + "_impl"), - ) + res = _get_marker_attr(found[0], self.project_name + "_impl") + if isinstance(res, HookimplConfiguration): + return res + if isinstance(res, Mapping): + return hookimpl_config_from_mapping(res) + return None + + def _discover_hookimpl_configuration( + self, plugin: _Plugin, name: str + ) -> HookimplConfiguration | None: + """Discover hookimpl configuration for registration. + + Prefer the modern marker attribute. Only call the deprecated + :meth:`parse_hookimpl_opts` when a subclass actually overrides it and + no modern configuration was found (pytest unmarked-hook concession). + """ + config = self._read_hookimpl_configuration(plugin, name) + if config is not None: + return config + parse_hookimpl_opts = type(self).parse_hookimpl_opts + if parse_hookimpl_opts is PluginManager.parse_hookimpl_opts: + return None + legacy = parse_hookimpl_opts(self, plugin, name) + if legacy is None: + return None + return hookimpl_config_from_mapping(legacy) + + def parse_hookimpl_opts(self, plugin: _Plugin, name: str) -> HookimplOpts | None: + """Return legacy dict-shaped hookimpl options, if any. + + .. deprecated:: + Thin pytest/support concession. Registration uses private discovery + of :class:`HookimplConfiguration` and only invokes this method when + a subclass overrides it and no modern configuration attribute was + found. Prefer marker-attached configuration objects. + """ + config = self._read_hookimpl_configuration(plugin, name) + if config is None: + return None + return cast(HookimplOpts, hookimpl_config_to_mapping(config)) def unregister( self, plugin: _Plugin | None = None, name: str | None = None @@ -322,15 +359,15 @@ def add_hookspecs(self, module_or_class: _Namespace) -> None: """ names = [] for name in dir(module_or_class): - spec_opts = self.parse_hookspec_opts(module_or_class, name) - if spec_opts is not None: + spec_config = self._discover_hookspec_configuration(module_or_class, name) + if spec_config is not None: hc: HookCaller | None = getattr(self.hook, name, None) if hc is None: - hc = HookCaller(name, self._hookexec, module_or_class, spec_opts) + hc = HookCaller(name, self._hookexec, module_or_class, spec_config) setattr(self.hook, name, hc) else: # Plugins registered this hook without knowing the spec. - hc.set_specification(module_or_class, spec_opts) + hc.set_specification(module_or_class, spec_config) for hookfunction in hc.get_hookimpls(): self._verify_hook(hc, hookfunction) names.append(name) @@ -340,19 +377,10 @@ def add_hookspecs(self, module_or_class: _Namespace) -> None: f"did not find any {self.project_name!r} hooks in {module_or_class!r}" ) - def parse_hookspec_opts( + def _read_hookspec_configuration( self, module_or_class: _Namespace, name: str - ) -> HookspecOpts | None: - """Try to obtain a hook specification from an item with the given name - in the given module or class which is being searched for hook specs. - - :returns: - The parsed hookspec options for defining a hook, or None to skip the - given item. - - This method can be overridden by ``PluginManager`` subclasses to - customize how hook specifications are picked up. By default, returns the - options for items decorated with :class:`HookspecMarker`. + ) -> HookspecConfiguration | None: + """Read a modern :class:`HookspecConfiguration` from a marked function. Discovery uses :func:`inspect.getattr_static` so properties and other descriptors are not executed. Only functions, classmethods, @@ -361,10 +389,48 @@ def parse_hookspec_opts( found = _static_hook_attr(module_or_class, name) if found is None: return None - return cast( - HookspecOpts | None, - _get_marker_opts(found[0], self.project_name + "_spec"), - ) + opts = _get_marker_attr(found[0], self.project_name + "_spec") + if isinstance(opts, HookspecConfiguration): + return opts + if isinstance(opts, Mapping): + return hookspec_config_from_mapping(opts) + return None + + def _discover_hookspec_configuration( + self, module_or_class: _Namespace, name: str + ) -> HookspecConfiguration | None: + """Discover hookspec configuration for ``add_hookspecs``. + + Prefer the modern marker attribute. Only call the deprecated + :meth:`parse_hookspec_opts` when a subclass actually overrides it and + no modern configuration was found. + """ + config = self._read_hookspec_configuration(module_or_class, name) + if config is not None: + return config + parse_hookspec_opts = type(self).parse_hookspec_opts + if parse_hookspec_opts is PluginManager.parse_hookspec_opts: + return None + legacy = parse_hookspec_opts(self, module_or_class, name) + if legacy is None: + return None + return hookspec_config_from_mapping(legacy) + + def parse_hookspec_opts( + self, module_or_class: _Namespace, name: str + ) -> HookspecOpts | None: + """Return legacy dict-shaped hookspec options, if any. + + .. deprecated:: + Thin pytest/support concession. ``add_hookspecs`` uses private + discovery of :class:`HookspecConfiguration` and only invokes this + method when a subclass overrides it and no modern configuration + attribute was found. Prefer marker-attached configuration objects. + """ + config = self._read_hookspec_configuration(module_or_class, name) + if config is None: + return None + return cast(HookspecOpts, hookspec_config_to_mapping(config)) def get_plugins(self) -> set[Any]: """Return a set of all registered plugin objects.""" diff --git a/src/pluggy/_pytest_compat.py b/src/pluggy/_pytest_compat.py new file mode 100644 index 00000000..e9d3b693 --- /dev/null +++ b/src/pluggy/_pytest_compat.py @@ -0,0 +1,55 @@ +"""Pytest/support compatibility helpers for legacy option encodings. + +The live pluggy API uses :class:`~pluggy.HookspecConfiguration` and +:class:`~pluggy.HookimplConfiguration`. This module keeps TypedDict shapes and +mapping conversion for pytest and other callers that still type or attach +dict-shaped options during migration. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TypedDict + +from ._config import hookimpl_config_from_mapping +from ._config import HookimplConfiguration +from ._config import hookspec_config_from_mapping +from ._config import HookspecConfiguration + + +class HookspecOpts(TypedDict): + """Legacy TypedDict for hook specification options. + + Prefer :class:`~pluggy.HookspecConfiguration`. Kept for pytest/typing + compatibility during migration. + """ + + firstresult: bool + historic: bool + warn_on_impl: Warning | None + warn_on_impl_args: Mapping[str, Warning] | None + + +class HookimplOpts(TypedDict): + """Legacy TypedDict for hook implementation options. + + Prefer :class:`~pluggy.HookimplConfiguration`. Kept for pytest/typing + compatibility during migration. + """ + + wrapper: bool + hookwrapper: bool + optionalhook: bool + tryfirst: bool + trylast: bool + specname: str | None + + +__all__ = [ + "HookimplConfiguration", + "HookimplOpts", + "HookspecConfiguration", + "HookspecOpts", + "hookimpl_config_from_mapping", + "hookspec_config_from_mapping", +] diff --git a/testing/test_configuration.py b/testing/test_configuration.py new file mode 100644 index 00000000..c7dbef0f --- /dev/null +++ b/testing/test_configuration.py @@ -0,0 +1,278 @@ +""" +Tests for configuration classes. +""" + +from __future__ import annotations + +import pytest + +from pluggy import HookimplConfiguration +from pluggy import HookimplMarker +from pluggy import HookspecConfiguration +from pluggy import HookspecMarker +from pluggy import PluginManager +from pluggy._config import hookimpl_config_from_mapping +from pluggy._config import hookspec_config_from_mapping + + +class TestHookspecConfiguration: + def test_basic_creation(self) -> None: + config = HookspecConfiguration() + assert config.firstresult is False + assert config.historic is False + assert config.warn_on_impl is None + assert config.warn_on_impl_args is None + + def test_firstresult(self) -> None: + config = HookspecConfiguration(firstresult=True) + assert config.firstresult is True + assert config.historic is False + + def test_historic(self) -> None: + config = HookspecConfiguration(historic=True) + assert config.firstresult is False + assert config.historic is True + + def test_historic_firstresult_validation(self) -> None: + with pytest.raises(ValueError, match="cannot have a historic firstresult"): + HookspecConfiguration(historic=True, firstresult=True) + + def test_warn_on_impl(self) -> None: + warning = UserWarning("test warning") + config = HookspecConfiguration(warn_on_impl=warning) + assert config.warn_on_impl is warning + + def test_warn_on_impl_args(self) -> None: + warnings_dict = {"arg1": UserWarning("arg1 warning")} + config = HookspecConfiguration(warn_on_impl_args=warnings_dict) + assert config.warn_on_impl_args is warnings_dict + + +class TestHookimplConfiguration: + def test_basic_creation(self) -> None: + config = HookimplConfiguration() + assert config.wrapper is False + assert config.hookwrapper is False + assert config.optionalhook is False + assert config.tryfirst is False + assert config.trylast is False + assert config.specname is None + + def test_wrapper(self) -> None: + config = HookimplConfiguration(wrapper=True) + assert config.wrapper is True + assert config.hookwrapper is False + + def test_hookwrapper(self) -> None: + config = HookimplConfiguration(hookwrapper=True) + assert config.wrapper is False + assert config.hookwrapper is True + + def test_both_wrappers_allowed(self) -> None: + """Both wrapper types are allowed at config level; validation is later.""" + config = HookimplConfiguration(wrapper=True, hookwrapper=True) + assert config.wrapper is True + assert config.hookwrapper is True + + def test_tryfirst(self) -> None: + config = HookimplConfiguration(tryfirst=True) + assert config.tryfirst is True + assert config.trylast is False + + def test_trylast(self) -> None: + config = HookimplConfiguration(trylast=True) + assert config.tryfirst is False + assert config.trylast is True + + def test_optionalhook(self) -> None: + config = HookimplConfiguration(optionalhook=True) + assert config.optionalhook is True + + def test_specname(self) -> None: + config = HookimplConfiguration(specname="custom_name") + assert config.specname == "custom_name" + + +class TestMappingShim: + def test_hookspec_config_from_mapping(self) -> None: + warning = UserWarning("w") + config = hookspec_config_from_mapping( + { + "firstresult": True, + "warn_on_impl": warning, + } + ) + assert config.firstresult is True + assert config.historic is False + assert config.warn_on_impl is warning + + def test_hookimpl_config_from_mapping(self) -> None: + config = hookimpl_config_from_mapping( + { + "tryfirst": True, + "specname": "other", + } + ) + assert config.tryfirst is True + assert config.specname == "other" + assert config.wrapper is False + + def test_read_hookimpl_accepts_legacy_dict_attribute(self) -> None: + pm = PluginManager("test") + + def method() -> str: + return "ok" + + # setattr, not attribute access: the marker is dynamic and must not + # be type-checked against the function object. + setattr(method, "test_impl", {"tryfirst": True}) # noqa: B010 + + class Plugin: + pass + + plugin = Plugin() + plugin.method = method # type: ignore[attr-defined] + config = pm._read_hookimpl_configuration(plugin, "method") + assert isinstance(config, HookimplConfiguration) + assert config.tryfirst is True + + def test_parse_hookimpl_opts_returns_legacy_dict(self) -> None: + hookimpl = HookimplMarker("test") + + @hookimpl(tryfirst=True) + def method() -> str: + return "ok" + + class Plugin: + pass + + plugin = Plugin() + plugin.method = method # type: ignore[attr-defined] + opts = PluginManager("test").parse_hookimpl_opts(plugin, "method") + assert opts == { + "wrapper": False, + "hookwrapper": False, + "optionalhook": False, + "tryfirst": True, + "trylast": False, + "specname": None, + } + + def test_read_hookspec_accepts_legacy_dict_attribute(self) -> None: + pm = PluginManager("test") + + class Spec: + def myhook(self) -> None: + pass + + setattr(Spec.myhook, "test_spec", {"firstresult": True}) # noqa: B010 + config = pm._read_hookspec_configuration(Spec, "myhook") + assert isinstance(config, HookspecConfiguration) + assert config.firstresult is True + + def test_discover_skips_parse_hookimpl_opts_unless_overridden(self) -> None: + calls: list[str] = [] + + class TrackingPluginManager(PluginManager): + def parse_hookimpl_opts(self, plugin: object, name: str): + calls.append(name) + return super().parse_hookimpl_opts(plugin, name) + + class Spec: + @HookspecMarker("test") + def marked(self) -> None: + pass + + def unmarked(self) -> None: + pass + + class Plugin: + @HookimplMarker("test") + def marked(self) -> str: + return "marked" + + def unmarked(self) -> str: + return "unmarked" + + pm = TrackingPluginManager("test") + pm.add_hookspecs(Spec) + pm.register(Plugin()) + # Marked impl is discovered privately; unmarked has no config and the + # override returns None, so parse_hookimpl_opts is only tried for names + # without a modern configuration attribute. + assert "marked" not in calls + assert "unmarked" in calls + + +def test_markers_attach_configuration_objects() -> None: + hookspec = HookspecMarker("test") + hookimpl = HookimplMarker("test") + + @hookspec(firstresult=True) + def myspec(arg: object) -> None: + pass + + @hookimpl(tryfirst=True) + def myimpl(arg: object) -> str: + return "x" + + spec_config = getattr(myspec, "test_spec") # noqa: B009 + impl_config = getattr(myimpl, "test_impl") # noqa: B009 + assert isinstance(spec_config, HookspecConfiguration) + assert spec_config.firstresult is True + assert isinstance(impl_config, HookimplConfiguration) + assert impl_config.tryfirst is True + + +def test_config_integration_with_hooks() -> None: + pm = PluginManager("test") + hookspec = HookspecMarker("test") + hookimpl = HookimplMarker("test") + + class MySpec: + @hookspec(firstresult=True) + def myhook(self, arg: object) -> None: + pass + + class Plugin1: + @hookimpl(trylast=True) + def myhook(self, arg: object) -> str: + return f"plugin1: {arg}" + + class Plugin2: + @hookimpl(tryfirst=True) + def myhook(self, arg: object) -> str: + return f"plugin2: {arg}" + + pm.add_hookspecs(MySpec) + pm.register(Plugin1()) + pm.register(Plugin2()) + + result = pm.hook.myhook(arg="test") + assert result == "plugin2: test" + + +def test_historic_hook_configuration() -> None: + pm = PluginManager("test") + hookspec = HookspecMarker("test") + hookimpl = HookimplMarker("test") + + results: list[str] = [] + + class MySpec: + @hookspec(historic=True) + def myhook(self, arg: object) -> None: + pass + + pm.add_hookspecs(MySpec) + pm.hook.myhook.call_historic( + kwargs={"arg": "call1"}, result_callback=results.append + ) + + class Plugin1: + @hookimpl + def myhook(self, arg: object) -> str: + return f"plugin1: {arg}" + + pm.register(Plugin1()) + assert "plugin1: call1" in results diff --git a/testing/test_details.py b/testing/test_details.py index 8df167f4..c73e43a5 100644 --- a/testing/test_details.py +++ b/testing/test_details.py @@ -16,9 +16,11 @@ def test_parse_hookimpl_override() -> None: class MyPluginManager(PluginManager): def parse_hookimpl_opts(self, module_or_class, name): opts = PluginManager.parse_hookimpl_opts(self, module_or_class, name) - if opts is None and name.startswith("x1"): - opts = {} # type: ignore[assignment] - return opts + if opts is not None: + return opts + if name.startswith("x1"): + return {} + return None class Plugin: def x1meth(self): diff --git a/testing/test_hookcaller.py b/testing/test_hookcaller.py index cdf79ca0..4a365c45 100644 --- a/testing/test_hookcaller.py +++ b/testing/test_hookcaller.py @@ -317,11 +317,11 @@ def he_myhook3(self, arg1) -> None: pm.add_hookspecs(HookSpec) assert pm.hook.he_myhook1.spec is not None - assert not pm.hook.he_myhook1.spec.opts["firstresult"] + assert not pm.hook.he_myhook1.spec.opts.firstresult assert pm.hook.he_myhook2.spec is not None - assert pm.hook.he_myhook2.spec.opts["firstresult"] + assert pm.hook.he_myhook2.spec.opts.firstresult assert pm.hook.he_myhook3.spec is not None - assert not pm.hook.he_myhook3.spec.opts["firstresult"] + assert not pm.hook.he_myhook3.spec.opts.firstresult @pytest.mark.parametrize("name", ["hookwrapper", "optionalhook", "tryfirst", "trylast"]) @@ -332,7 +332,7 @@ def he_myhook1(arg1) -> None: pass if val: - assert he_myhook1.example_impl.get(name) + assert getattr(he_myhook1.example_impl, name) else: assert not hasattr(he_myhook1, name) From e1479c4caaf39c4450eaeaf7df5f31d55022087a Mon Sep 17 00:00:00 2001 From: Ronny Pfannschmidt Date: Fri, 24 Jul 2026 11:20:10 +0200 Subject: [PATCH 3/5] feat(decorators): attach Hook*Configuration objects on marked functions Complete design step 03: markers already attach configuration objects since step 02; this finishes the step by storing the spec configuration as HookSpec.config (try-claude naming) with a deprecated .opts alias, reading .config in HookCaller firstresult resolution, and covering decoration-time historic+firstresult validation and configuration attachment with tests. Co-Authored-By: Claude Fable 5 --- changelog/706.trivial.rst | 3 +++ src/pluggy/_caller.py | 4 ++-- src/pluggy/_decorators.py | 19 ++++++++++++++----- testing/test_configuration.py | 28 ++++++++++++++++++++++++++++ testing/test_hookcaller.py | 6 +++--- 5 files changed, 50 insertions(+), 10 deletions(-) create mode 100644 changelog/706.trivial.rst diff --git a/changelog/706.trivial.rst b/changelog/706.trivial.rst new file mode 100644 index 00000000..88d43f7e --- /dev/null +++ b/changelog/706.trivial.rst @@ -0,0 +1,3 @@ +``HookSpec`` now stores its :class:`pluggy.HookspecConfiguration` as +``config``; the old ``opts`` attribute remains as a deprecated alias +property. diff --git a/src/pluggy/_caller.py b/src/pluggy/_caller.py index 15ce95d7..08e1820d 100644 --- a/src/pluggy/_caller.py +++ b/src/pluggy/_caller.py @@ -186,7 +186,7 @@ def __call__(self, **kwargs: object) -> Any: "Cannot directly call a historic hook - use call_historic instead." ) self._verify_all_args_are_provided(kwargs) - firstresult = self.spec.opts.firstresult if self.spec else False + firstresult = self.spec.config.firstresult if self.spec else False # Copy because plugins may register other plugins during iteration (#438). return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) @@ -241,7 +241,7 @@ def call_extra( ): i -= 1 hookimpls.insert(i + 1, hookimpl) - firstresult = self.spec.opts.firstresult if self.spec else False + firstresult = self.spec.config.firstresult if self.spec else False return self._hookexec(self.name, hookimpls, kwargs, firstresult) def _maybe_apply_history(self, method: HookImpl) -> None: diff --git a/src/pluggy/_decorators.py b/src/pluggy/_decorators.py index 713c978e..0c80e3fb 100644 --- a/src/pluggy/_decorators.py +++ b/src/pluggy/_decorators.py @@ -327,17 +327,17 @@ def varnames( class HookSpec: __slots__ = ( "argnames", + "config", "function", "kwargnames", "name", "namespace", - "opts", "warn_on_impl", "warn_on_impl_args", ) def __init__( - self, namespace: _Namespace, name: str, opts: HookspecConfiguration + self, namespace: _Namespace, name: str, config: HookspecConfiguration ) -> None: self.namespace = namespace self.name = name @@ -348,6 +348,15 @@ def __init__( self.argnames, self.kwargnames = varnames( self.function, legacy_noself=legacy_noself ) - self.opts = opts - self.warn_on_impl = opts.warn_on_impl - self.warn_on_impl_args = opts.warn_on_impl_args + self.config = config + self.warn_on_impl = config.warn_on_impl + self.warn_on_impl_args = config.warn_on_impl_args + + @property + def opts(self) -> HookspecConfiguration: + """Alias for :attr:`config`. + + .. deprecated:: + Use :attr:`config` instead. + """ + return self.config diff --git a/testing/test_configuration.py b/testing/test_configuration.py index c7dbef0f..22174cdf 100644 --- a/testing/test_configuration.py +++ b/testing/test_configuration.py @@ -224,6 +224,34 @@ def myimpl(arg: object) -> str: assert impl_config.tryfirst is True +def test_historic_firstresult_raises_at_decoration_time() -> None: + hookspec = HookspecMarker("test") + + with pytest.raises(ValueError, match="cannot have a historic firstresult"): + + @hookspec(historic=True, firstresult=True) + def myspec() -> None: + pass + + +def test_hookspec_stores_configuration() -> None: + pm = PluginManager("test") + hookspec = HookspecMarker("test") + + class Spec: + @hookspec(firstresult=True) + def myhook(self, arg: object) -> None: + pass + + pm.add_hookspecs(Spec) + spec = pm.hook.myhook.spec + assert spec is not None + assert isinstance(spec.config, HookspecConfiguration) + assert spec.config.firstresult is True + # Deprecated alias. + assert spec.opts is spec.config + + def test_config_integration_with_hooks() -> None: pm = PluginManager("test") hookspec = HookspecMarker("test") diff --git a/testing/test_hookcaller.py b/testing/test_hookcaller.py index 4a365c45..49b01e5b 100644 --- a/testing/test_hookcaller.py +++ b/testing/test_hookcaller.py @@ -317,11 +317,11 @@ def he_myhook3(self, arg1) -> None: pm.add_hookspecs(HookSpec) assert pm.hook.he_myhook1.spec is not None - assert not pm.hook.he_myhook1.spec.opts.firstresult + assert not pm.hook.he_myhook1.spec.config.firstresult assert pm.hook.he_myhook2.spec is not None - assert pm.hook.he_myhook2.spec.opts.firstresult + assert pm.hook.he_myhook2.spec.config.firstresult assert pm.hook.he_myhook3.spec is not None - assert not pm.hook.he_myhook3.spec.opts.firstresult + assert not pm.hook.he_myhook3.spec.config.firstresult @pytest.mark.parametrize("name", ["hookwrapper", "optionalhook", "tryfirst", "trylast"]) From a0a706ee01308c976f23b05ec6bf9e0616f45ace Mon Sep 17 00:00:00 2001 From: Ronny Pfannschmidt Date: Fri, 24 Jul 2026 12:30:04 +0200 Subject: [PATCH 4/5] feat(implementation): add NormalImpl, WrapperImpl, and CompletionHook setup API Complete design step 04: - HookImpl becomes a base class storing hookimpl_config (deprecated .opts alias kept) with arg binding moved to _get_call_args. - NormalImpl / WrapperImpl subclasses validate their configuration; HookimplConfiguration.create_hookimpl() returns the right subclass (fixing the try-claude footgun of bare HookImpl for normals). - WrapperImpl.setup_and_get_completion_hook() runs wrapper setup and returns a CompletionHook (runtime-checkable Protocol) that owns teardown, adapting old-style hookwrappers uniformly. - Registration and call_extra construct impls via create_hookimpl; multicall binds args via _get_call_args. Full dual-sequence multicall rewiring lands with design step 05. Co-Authored-By: Claude Fable 5 --- changelog/707.feature.rst | 9 ++ docs/api_reference.rst | 8 ++ src/pluggy/__init__.py | 4 + src/pluggy/_caller.py | 4 +- src/pluggy/_config.py | 29 +++++ src/pluggy/_execution.py | 8 +- src/pluggy/_hooks.py | 6 ++ src/pluggy/_impl.py | 165 +++++++++++++++++++++++++++-- src/pluggy/_manager.py | 2 +- testing/test_details.py | 2 +- testing/test_impl.py | 218 ++++++++++++++++++++++++++++++++++++++ 11 files changed, 433 insertions(+), 22 deletions(-) create mode 100644 changelog/707.feature.rst create mode 100644 testing/test_impl.py diff --git a/changelog/707.feature.rst b/changelog/707.feature.rst new file mode 100644 index 00000000..cbdca55e --- /dev/null +++ b/changelog/707.feature.rst @@ -0,0 +1,9 @@ +Hook implementations are now represented by dedicated types: +:class:`pluggy.NormalImpl` for normal implementations and +:class:`pluggy.WrapperImpl` for (old- and new-style) wrappers, both +subclasses of :class:`pluggy.HookImpl`. +``HookimplConfiguration.create_hookimpl()`` selects the appropriate +subclass, and ``WrapperImpl.setup_and_get_completion_hook()`` exposes +wrapper setup/teardown as a ``CompletionHook`` callback. +``HookImpl`` now stores its configuration as ``hookimpl_config``; the old +``opts`` attribute remains as a deprecated alias property. diff --git a/docs/api_reference.rst b/docs/api_reference.rst index 7d19a4a6..a62272f7 100644 --- a/docs/api_reference.rst +++ b/docs/api_reference.rst @@ -40,6 +40,14 @@ API Reference .. autoclass:: pluggy.HookImpl() :members: +.. autoclass:: pluggy.NormalImpl() + :show-inheritance: + :members: + +.. autoclass:: pluggy.WrapperImpl() + :show-inheritance: + :members: + .. autoclass:: pluggy.HookspecConfiguration() :members: diff --git a/src/pluggy/__init__.py b/src/pluggy/__init__.py index 83064d90..d562a1b9 100644 --- a/src/pluggy/__init__.py +++ b/src/pluggy/__init__.py @@ -9,11 +9,13 @@ "HookspecConfiguration", "HookspecMarker", "HookspecOpts", + "NormalImpl", "PluggyTeardownRaisedWarning", "PluggyWarning", "PluginManager", "PluginValidationError", "Result", + "WrapperImpl", "__version__", ] from ._config import HookimplConfiguration @@ -23,6 +25,8 @@ from ._hooks import HookimplMarker from ._hooks import HookRelay from ._hooks import HookspecMarker +from ._hooks import NormalImpl +from ._hooks import WrapperImpl from ._manager import PluginManager from ._manager import PluginValidationError from ._pytest_compat import HookimplOpts diff --git a/src/pluggy/_caller.py b/src/pluggy/_caller.py index 08e1820d..454b595f 100644 --- a/src/pluggy/_caller.py +++ b/src/pluggy/_caller.py @@ -227,10 +227,10 @@ def call_extra( "Cannot directly call a historic hook - use call_historic instead." ) self._verify_all_args_are_provided(kwargs) - opts = HookimplConfiguration() + config = HookimplConfiguration() hookimpls = self._hookimpls.copy() for method in methods: - hookimpl = HookImpl(None, "", method, opts) + hookimpl = config.create_hookimpl(None, "", method) # Find last non-tryfirst nonwrapper method. i = len(hookimpls) - 1 while i >= 0 and ( diff --git a/src/pluggy/_config.py b/src/pluggy/_config.py index 48ead414..64e374ea 100644 --- a/src/pluggy/_config.py +++ b/src/pluggy/_config.py @@ -8,6 +8,14 @@ from typing import Any from typing import Final from typing import final +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from ._impl import _HookImplFunction + from ._impl import _Plugin + from ._impl import NormalImpl + from ._impl import WrapperImpl @final @@ -98,6 +106,27 @@ def __init__( #: The name of the hook specification to match, see :ref:`specname`. self.specname = specname + def create_hookimpl( + self, + plugin: _Plugin, + plugin_name: str, + function: _HookImplFunction[object], + ) -> NormalImpl | WrapperImpl: + """Create the appropriate :class:`HookImpl` subclass for this + configuration. + + Wrapper configurations produce a :class:`WrapperImpl`; all others + produce a :class:`NormalImpl`. + """ + # Local import to avoid a circular import with the implementation + # module. + from ._impl import NormalImpl + from ._impl import WrapperImpl + + if self.wrapper or self.hookwrapper: + return WrapperImpl(plugin, plugin_name, function, self) + return NormalImpl(plugin, plugin_name, function, self) + def __repr__(self) -> str: attrs = [ f"{slot}={getattr(self, slot)!r}" diff --git a/src/pluggy/_execution.py b/src/pluggy/_execution.py index cda5210d..12a03b76 100644 --- a/src/pluggy/_execution.py +++ b/src/pluggy/_execution.py @@ -14,7 +14,6 @@ import warnings from ._impl import HookImpl -from ._result import HookCallError from ._result import Result from ._warnings import PluggyTeardownRaisedWarning @@ -96,12 +95,7 @@ def _multicall( teardowns: list[Teardown] = [] try: # run impl and wrapper setup functions in a loop for hook_impl in reversed(hook_impls): - try: - args = [caller_kwargs[argname] for argname in hook_impl.argnames] - except KeyError as e: - raise HookCallError( - f"hook call must provide argument {e.args[0]!r}" - ) from e + args = hook_impl._get_call_args(caller_kwargs) if hook_impl.hookwrapper: function_gen = run_old_style_hookwrapper(hook_impl, hook_name, args) diff --git a/src/pluggy/_hooks.py b/src/pluggy/_hooks.py index 55197772..ef3a76f9 100644 --- a/src/pluggy/_hooks.py +++ b/src/pluggy/_hooks.py @@ -22,10 +22,14 @@ from ._decorators import varnames from ._impl import _HookImplFunction from ._impl import _Plugin +from ._impl import CompletionHook from ._impl import HookImpl +from ._impl import NormalImpl +from ._impl import WrapperImpl __all__ = [ + "CompletionHook", "HookCaller", "HookImpl", "HookRelay", @@ -34,6 +38,8 @@ "HookimplMarker", "HookspecConfiguration", "HookspecMarker", + "NormalImpl", + "WrapperImpl", "_HookCaller", "_HookExec", "_HookImplFunction", diff --git a/src/pluggy/_impl.py b/src/pluggy/_impl.py index 5a2043b6..ba85c435 100644 --- a/src/pluggy/_impl.py +++ b/src/pluggy/_impl.py @@ -6,13 +6,18 @@ from collections.abc import Callable from collections.abc import Generator +from collections.abc import Mapping +from typing import cast from typing import Final from typing import final +from typing import Protocol +from typing import runtime_checkable from typing import TypeAlias from typing import TypeVar from ._config import HookimplConfiguration from ._decorators import varnames +from ._result import HookCallError from ._result import Result @@ -22,17 +27,31 @@ _HookImplFunction: TypeAlias = Callable[..., _T | Generator[None, Result[_T], None]] -@final +@runtime_checkable +class CompletionHook(Protocol): + """Teardown callback returned by :meth:`WrapperImpl.setup_and_get_completion_hook`. + + Receives the current ``(result, exception)`` outcome of the hook call and + returns the possibly replaced ``(result, exception)`` pair. + """ + + def __call__( + self, + result: object | list[object] | None, + exception: BaseException | None, + ) -> tuple[object | list[object] | None, BaseException | None]: ... + + class HookImpl: - """A hook implementation in a :class:`HookCaller`.""" + """Base class for hook implementations in a :class:`HookCaller`.""" __slots__ = ( "argnames", "function", + "hookimpl_config", "hookwrapper", "kwargnames", "optionalhook", - "opts", "plugin", "plugin_name", "tryfirst", @@ -45,7 +64,7 @@ def __init__( plugin: _Plugin, plugin_name: str, function: _HookImplFunction[object], - hook_impl_opts: HookimplConfiguration, + hook_impl_config: HookimplConfiguration, ) -> None: """:meta private:""" #: The hook implementation function. @@ -59,23 +78,147 @@ def __init__( self.plugin: Final = plugin #: The :class:`HookimplConfiguration` used to configure this hook #: implementation. - self.opts: Final = hook_impl_opts + self.hookimpl_config: Final = hook_impl_config #: The name of the plugin which defined this hook implementation. self.plugin_name: Final = plugin_name #: Whether the hook implementation is a :ref:`wrapper `. - self.wrapper: Final = hook_impl_opts.wrapper + self.wrapper: Final = hook_impl_config.wrapper #: Whether the hook implementation is an :ref:`old-style wrapper #: `. - self.hookwrapper: Final = hook_impl_opts.hookwrapper + self.hookwrapper: Final = hook_impl_config.hookwrapper #: Whether validation against a hook specification is :ref:`optional #: `. - self.optionalhook: Final = hook_impl_opts.optionalhook + self.optionalhook: Final = hook_impl_config.optionalhook #: Whether to try to order this hook implementation :ref:`first #: `. - self.tryfirst: Final = hook_impl_opts.tryfirst + self.tryfirst: Final = hook_impl_config.tryfirst #: Whether to try to order this hook implementation :ref:`last #: `. - self.trylast: Final = hook_impl_opts.trylast + self.trylast: Final = hook_impl_config.trylast + + @property + def opts(self) -> HookimplConfiguration: + """Alias for :attr:`hookimpl_config`. + + .. deprecated:: + Use :attr:`hookimpl_config` instead. + """ + return self.hookimpl_config + + def _get_call_args(self, caller_kwargs: Mapping[str, object]) -> list[object]: + """Extract the positional arguments for calling this hook implementation. + + :raises HookCallError: If a required argument is missing. + """ + try: + return [caller_kwargs[argname] for argname in self.argnames] + except KeyError as e: + raise HookCallError(f"hook call must provide argument {e.args[0]!r}") from e def __repr__(self) -> str: - return f"" + return ( + f"<{type(self).__name__} " + f"plugin_name={self.plugin_name!r}, plugin={self.plugin!r}>" + ) + + +@final +class NormalImpl(HookImpl): + """A normal (non-wrapper) hook implementation in a :class:`HookCaller`.""" + + def __init__( + self, + plugin: _Plugin, + plugin_name: str, + function: _HookImplFunction[object], + hook_impl_config: HookimplConfiguration, + ) -> None: + """:meta private:""" + if hook_impl_config.wrapper or hook_impl_config.hookwrapper: + raise ValueError( + "NormalImpl cannot be used for wrapper implementations. " + "Use WrapperImpl instead." + ) + super().__init__(plugin, plugin_name, function, hook_impl_config) + + +@final +class WrapperImpl(HookImpl): + """A wrapper hook implementation in a :class:`HookCaller`.""" + + def __init__( + self, + plugin: _Plugin, + plugin_name: str, + function: _HookImplFunction[object], + hook_impl_config: HookimplConfiguration, + ) -> None: + """:meta private:""" + if not (hook_impl_config.wrapper or hook_impl_config.hookwrapper): + raise ValueError( + "WrapperImpl can only be used for wrapper implementations. " + "Use NormalImpl for normal implementations." + ) + super().__init__(plugin, plugin_name, function, hook_impl_config) + + def setup_and_get_completion_hook( + self, hook_name: str, caller_kwargs: Mapping[str, object] + ) -> CompletionHook: + """Run the wrapper setup phase and return its :class:`CompletionHook`. + + Old-style hookwrappers and new-style wrappers are handled uniformly by + adapting old-style wrappers via ``run_old_style_hookwrapper``. + + The returned completion hook performs the teardown: it sends the + current outcome into the wrapper generator (or throws the current + exception) and returns the possibly replaced ``(result, exception)`` + pair. + """ + # Local import to avoid a circular import with the execution module. + from ._execution import _raise_wrapfail + from ._execution import run_old_style_hookwrapper + + args = self._get_call_args(caller_kwargs) + + wrapper_gen: Generator[None, object, object] + if self.hookwrapper: + wrapper_gen = run_old_style_hookwrapper(self, hook_name, args) + else: + wrapper_gen = cast(Generator[None, object, object], self.function(*args)) + + try: + next(wrapper_gen) # first yield / setup phase + except StopIteration: + _raise_wrapfail(wrapper_gen, "did not yield") + + def completion_hook( + result: object | list[object] | None, exception: BaseException | None + ) -> tuple[object | list[object] | None, BaseException | None]: + try: + if exception is not None: + try: + wrapper_gen.throw(exception) + except RuntimeError as re: + # StopIteration from generator causes RuntimeError + # even for coroutine usage - see #544 + if ( + isinstance(exception, StopIteration) + and re.__cause__ is exception + ): + wrapper_gen.close() + return result, exception + else: + raise + else: + wrapper_gen.send(result) + # Following is unreachable for a well behaved hook wrapper. + # Try to force finalizers otherwise postponed till GC action. + # Note: close() may raise if generator handles GeneratorExit. + wrapper_gen.close() + _raise_wrapfail(wrapper_gen, "has second yield") + except StopIteration as si: + return si.value, None + except BaseException as e: + return result, e + + return completion_hook diff --git a/src/pluggy/_manager.py b/src/pluggy/_manager.py index 506342d6..859f2462 100644 --- a/src/pluggy/_manager.py +++ b/src/pluggy/_manager.py @@ -235,7 +235,7 @@ def register(self, plugin: _Plugin, name: str | None = None) -> str | None: f"{plugin!r}.{attr_name} is not a hookable attribute" ) method: _HookImplFunction[object] = found[1] - hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_config) + hookimpl = hookimpl_config.create_hookimpl(plugin, plugin_name, method) hook_name = hookimpl_config.specname or attr_name hook: HookCaller | None = getattr(self.hook, hook_name, None) if hook is None: diff --git a/testing/test_details.py b/testing/test_details.py index c73e43a5..546f7e92 100644 --- a/testing/test_details.py +++ b/testing/test_details.py @@ -224,7 +224,7 @@ def myhook(self): plugin = Plugin() pname = pm.register(plugin) assert repr(pm.hook.myhook.get_hookimpls()[0]) == ( - f"" + f"" ) diff --git a/testing/test_impl.py b/testing/test_impl.py new file mode 100644 index 00000000..dcfeadca --- /dev/null +++ b/testing/test_impl.py @@ -0,0 +1,218 @@ +""" +Tests for the HookImpl hierarchy and the CompletionHook setup API. +""" + +from __future__ import annotations + +from collections.abc import Callable +from collections.abc import Generator +from typing import Any + +import pytest + +from pluggy import HookCallError +from pluggy import HookImpl +from pluggy import HookimplConfiguration +from pluggy import HookimplMarker +from pluggy import HookspecMarker +from pluggy import NormalImpl +from pluggy import PluginManager +from pluggy import WrapperImpl +from pluggy._impl import CompletionHook + + +hookspec = HookspecMarker("example") +hookimpl = HookimplMarker("example") + + +def func(arg: object) -> object: + return arg + + +def wrapper_func(arg: object) -> Generator[None, object, object]: + return (yield) + + +class TestCreateHookimpl: + def test_normal_config_returns_normal_impl(self) -> None: + config = HookimplConfiguration() + impl = config.create_hookimpl(None, "test", func) + assert type(impl) is NormalImpl + assert isinstance(impl, HookImpl) + assert impl.hookimpl_config is config + + def test_wrapper_config_returns_wrapper_impl(self) -> None: + config = HookimplConfiguration(wrapper=True) + impl = config.create_hookimpl(None, "test", wrapper_func) + assert type(impl) is WrapperImpl + + def test_hookwrapper_config_returns_wrapper_impl(self) -> None: + config = HookimplConfiguration(hookwrapper=True) + impl = config.create_hookimpl(None, "test", wrapper_func) + assert type(impl) is WrapperImpl + + def test_normal_impl_rejects_wrapper_config(self) -> None: + config = HookimplConfiguration(wrapper=True) + with pytest.raises(ValueError, match="Use WrapperImpl"): + NormalImpl(None, "test", wrapper_func, config) + + def test_wrapper_impl_rejects_normal_config(self) -> None: + config = HookimplConfiguration() + with pytest.raises(ValueError, match="Use NormalImpl"): + WrapperImpl(None, "test", func, config) + + def test_opts_alias(self) -> None: + config = HookimplConfiguration(tryfirst=True) + impl = config.create_hookimpl(None, "test", func) + assert impl.opts is config + + +class TestGetCallArgs: + def test_binds_in_argname_order(self) -> None: + def f(b: object, a: object) -> None: + pass + + impl = HookimplConfiguration().create_hookimpl(None, "test", f) + assert impl._get_call_args({"a": 1, "b": 2, "extra": 3}) == [2, 1] + + def test_missing_argument_raises_hook_call_error(self) -> None: + impl = HookimplConfiguration().create_hookimpl(None, "test", func) + with pytest.raises(HookCallError, match="must provide argument 'arg'"): + impl._get_call_args({}) + + +def make_wrapper_impl( + function: Callable[..., Any], *, hookwrapper: bool = False +) -> WrapperImpl: + config = HookimplConfiguration(wrapper=not hookwrapper, hookwrapper=hookwrapper) + impl = config.create_hookimpl(None, "test", function) + assert isinstance(impl, WrapperImpl) + return impl + + +class TestSetupAndGetCompletionHook: + def test_returns_completion_hook_protocol_instance(self) -> None: + impl = make_wrapper_impl(wrapper_func) + completion = impl.setup_and_get_completion_hook("myhook", {"arg": 1}) + assert isinstance(completion, CompletionHook) + assert completion(21, None) == (21, None) + + def test_setup_runs_code_before_yield(self) -> None: + events: list[str] = [] + + def wrapper() -> Generator[None, object, object]: + events.append("setup") + res = yield + events.append("teardown") + return res + + impl = make_wrapper_impl(wrapper) + completion = impl.setup_and_get_completion_hook("myhook", {}) + assert events == ["setup"] + assert completion("x", None) == ("x", None) + assert events == ["setup", "teardown"] + + def test_completion_replaces_result(self) -> None: + def wrapper() -> Generator[None, object, object]: + res = yield + assert isinstance(res, int) + return res + 1 + + impl = make_wrapper_impl(wrapper) + completion = impl.setup_and_get_completion_hook("myhook", {}) + assert completion(41, None) == (42, None) + + def test_completion_can_swallow_exception(self) -> None: + def wrapper() -> Generator[None, object, object]: + try: + yield + except ValueError: + return "fallback" + raise AssertionError("unreachable") + + impl = make_wrapper_impl(wrapper) + completion = impl.setup_and_get_completion_hook("myhook", {}) + result, exception = completion(None, ValueError("boom")) + assert result == "fallback" + assert exception is None + + def test_completion_passes_through_unhandled_exception(self) -> None: + impl = make_wrapper_impl(wrapper_func) + completion = impl.setup_and_get_completion_hook("myhook", {"arg": 1}) + exc = ValueError("boom") + result, exception = completion("kept", exc) + assert result == "kept" + assert exception is exc + + def test_completion_can_raise_new_exception(self) -> None: + def wrapper() -> Generator[None, object, object]: + yield + raise RuntimeError("replaced") + + impl = make_wrapper_impl(wrapper) + completion = impl.setup_and_get_completion_hook("myhook", {}) + result, exception = completion("x", None) + assert result == "x" + assert isinstance(exception, RuntimeError) + assert str(exception) == "replaced" + + def test_did_not_yield_raises(self) -> None: + def no_yield() -> Generator[None, object, object]: + return "nope" + yield # type: ignore[unreachable] # pragma: no cover + + impl = make_wrapper_impl(no_yield) + with pytest.raises(RuntimeError, match="did not yield"): + impl.setup_and_get_completion_hook("myhook", {}) + + def test_second_yield_raises(self) -> None: + def two_yields() -> Generator[None, object, None]: + yield + yield + + impl = make_wrapper_impl(two_yields) + completion = impl.setup_and_get_completion_hook("myhook", {}) + result, exception = completion("x", None) + assert result == "x" + assert isinstance(exception, RuntimeError) + assert "has second yield" in str(exception) + + def test_old_style_hookwrapper_receives_result_object(self) -> None: + seen: list[object] = [] + + def old_style(arg: object) -> Generator[None, object, None]: + outcome = yield + seen.append(outcome) + outcome.force_result(f"forced: {arg}") # type: ignore[attr-defined] + + impl = make_wrapper_impl(old_style, hookwrapper=True) + completion = impl.setup_and_get_completion_hook("myhook", {"arg": "a"}) + result, exception = completion("orig", None) + assert result == "forced: a" + assert exception is None + assert seen and seen[0].__class__.__name__ == "Result" + + +class TestRegistrationCreatesSubclasses: + def test_registered_impl_types(self) -> None: + class Spec: + @hookspec + def myhook(self, arg: object) -> None: + pass + + class Plugin: + @hookimpl + def myhook(self, arg: object) -> object: + return arg + + @hookimpl(wrapper=True) + def myhook_wrapper(self, arg: object) -> Generator[None, object, object]: + return (yield) + + pm = PluginManager("example") + pm.add_hookspecs(Spec) + pm.register(Plugin()) + impls = {type(impl).__name__ for impl in pm.hook.myhook.get_hookimpls()} + assert impls == {"NormalImpl"} + wrapper_impls = pm.hook.myhook_wrapper.get_hookimpls() + assert {type(impl).__name__ for impl in wrapper_impls} == {"WrapperImpl"} From 54700ad9357264227de9a2cda3d55e9837fdfee4 Mon Sep 17 00:00:00 2001 From: Ronny Pfannschmidt Date: Fri, 24 Jul 2026 15:11:47 +0200 Subject: [PATCH 5/5] refactor(caller): Protocol HookCaller, split callers, CompletionHook multicall Complete design step 05: - HookCaller is now a @runtime_checkable Protocol; concrete callers are NormalHookCaller (split list[NormalImpl] / list[WrapperImpl] storage), HistoricHookCaller (memorize/replay, rejects wrappers) and SubsetHookCaller (read-only filtered proxy). _HookCaller and _SubsetHookCaller remain as compat aliases. - _multicall takes dual sequences and orchestrates phases only: wrapper setup collects CompletionHooks, normals run, completion hooks run LIFO and may replace (result, exception) - no wrapper flag branching. - add_hookspecs hands a NormalHookCaller over to a HistoricHookCaller when a historic spec arrives after impl registration. - PluginManager._hookexec and tracing use the dual-sequence signature; monitoring callbacks keep receiving one combined impl list. - HookSpec.verify_all_args_are_provided replaces the caller-side helper; set_specification accepts a config object or legacy mapping (shim). - New tests: protocol isinstance for all concretes, historic handover, historic direct-call/call_extra rejection. Co-Authored-By: Claude Fable 5 --- changelog/708.feature.rst | 12 + docs/api_reference.rst | 11 + src/pluggy/__init__.py | 6 + src/pluggy/_caller.py | 554 +++++++++++++++++++++++++--------- src/pluggy/_decorators.py | 23 ++ src/pluggy/_execution.py | 118 +++----- src/pluggy/_hooks.py | 6 + src/pluggy/_manager.py | 70 ++++- testing/benchmark.py | 14 +- testing/test_hookcaller.py | 124 ++++++-- testing/test_multicall.py | 17 +- testing/test_pluginmanager.py | 2 +- 12 files changed, 700 insertions(+), 257 deletions(-) create mode 100644 changelog/708.feature.rst diff --git a/changelog/708.feature.rst b/changelog/708.feature.rst new file mode 100644 index 00000000..7e0e6608 --- /dev/null +++ b/changelog/708.feature.rst @@ -0,0 +1,12 @@ +:class:`pluggy.HookCaller` is now a runtime-checkable +:class:`~typing.Protocol` implemented by the new concrete callers +:class:`pluggy.NormalHookCaller` (split normal/wrapper implementation +lists), :class:`pluggy.HistoricHookCaller` (call memorization and replay, +no wrappers) and :class:`pluggy.SubsetHookCaller`. +``isinstance(caller, HookCaller)`` keeps working for all of them. + +The hook execution engine now runs a dual-sequence multicall: wrappers own +their setup/teardown through ``CompletionHook`` callbacks which run LIFO +after the normal implementations, removing all wrapper flag branching from +the hot loop. Hook call monitoring callbacks still receive a single +combined implementation list. diff --git a/docs/api_reference.rst b/docs/api_reference.rst index a62272f7..c4ce49ae 100644 --- a/docs/api_reference.rst +++ b/docs/api_reference.rst @@ -29,6 +29,17 @@ API Reference :members: :special-members: __call__ +.. autoclass:: pluggy.NormalHookCaller() + :members: + :special-members: __call__ + +.. autoclass:: pluggy.HistoricHookCaller() + :members: + :special-members: __call__ + +.. autoclass:: pluggy.SubsetHookCaller() + :members: + .. autoclass:: pluggy.HookCallError() :show-inheritance: :members: diff --git a/src/pluggy/__init__.py b/src/pluggy/__init__.py index d562a1b9..d3858dfa 100644 --- a/src/pluggy/__init__.py +++ b/src/pluggy/__init__.py @@ -1,4 +1,5 @@ __all__ = [ + "HistoricHookCaller", "HookCallError", "HookCaller", "HookImpl", @@ -9,23 +10,28 @@ "HookspecConfiguration", "HookspecMarker", "HookspecOpts", + "NormalHookCaller", "NormalImpl", "PluggyTeardownRaisedWarning", "PluggyWarning", "PluginManager", "PluginValidationError", "Result", + "SubsetHookCaller", "WrapperImpl", "__version__", ] from ._config import HookimplConfiguration from ._config import HookspecConfiguration +from ._hooks import HistoricHookCaller from ._hooks import HookCaller from ._hooks import HookImpl from ._hooks import HookimplMarker from ._hooks import HookRelay from ._hooks import HookspecMarker +from ._hooks import NormalHookCaller from ._hooks import NormalImpl +from ._hooks import SubsetHookCaller from ._hooks import WrapperImpl from ._manager import PluginManager from ._manager import PluginValidationError diff --git a/src/pluggy/_caller.py b/src/pluggy/_caller.py index 454b595f..b51b12f6 100644 --- a/src/pluggy/_caller.py +++ b/src/pluggy/_caller.py @@ -6,28 +6,124 @@ from collections.abc import Callable from collections.abc import Mapping +from collections.abc import MutableSequence from collections.abc import Sequence from collections.abc import Set as AbstractSet from typing import Any +from typing import cast from typing import Final from typing import final +from typing import Protocol +from typing import runtime_checkable from typing import TYPE_CHECKING from typing import TypeAlias -import warnings +from typing import TypeVar from ._config import HookimplConfiguration +from ._config import hookspec_config_from_mapping from ._config import HookspecConfiguration from ._decorators import _Namespace from ._decorators import HookSpec from ._impl import _Plugin from ._impl import HookImpl +from ._impl import NormalImpl +from ._impl import WrapperImpl _HookExec: TypeAlias = Callable[ - [str, Sequence[HookImpl], Mapping[str, object], bool], - object | list[object], + [str, Sequence[NormalImpl], Sequence[WrapperImpl], Mapping[str, object], bool], + "object | list[object]", ] +_T_HookImpl = TypeVar("_T_HookImpl", bound=HookImpl) + + +def _insert_hookimpl_into_list( + hookimpl: _T_HookImpl, target_list: MutableSequence[_T_HookImpl] +) -> None: + """Insert a hookimpl into the target list maintaining proper ordering. + + The ordering is: [trylast, normal, tryfirst]. + """ + if hookimpl.trylast: + target_list.insert(0, hookimpl) + elif hookimpl.tryfirst: + target_list.append(hookimpl) + else: + # find last non-tryfirst method + i = len(target_list) - 1 + while i >= 0 and target_list[i].tryfirst: + i -= 1 + target_list.insert(i + 1, hookimpl) + + +def _coerce_spec_config( + spec_config: HookspecConfiguration | Mapping[str, Any], +) -> HookspecConfiguration: + """Accept a configuration object or a legacy mapping (pytest shim).""" + if isinstance(spec_config, HookspecConfiguration): + return spec_config + return hookspec_config_from_mapping(spec_config) + + +@runtime_checkable +class HookCaller(Protocol): + """Protocol defining the interface for hook callers. + + .. versionchanged:: 1.7 + ``HookCaller`` is now a :class:`~typing.Protocol` (runtime checkable). + The concrete implementations are :class:`NormalHookCaller`, + :class:`HistoricHookCaller` and ``SubsetHookCaller``. + """ + + @property + def name(self) -> str: + """Name of the hook getting called.""" + ... + + @property + def spec(self) -> HookSpec | None: + """The hook specification, if any.""" + ... + + def has_spec(self) -> bool: + """Whether this caller has a hook specification.""" + ... + + def is_historic(self) -> bool: + """Whether this caller is :ref:`historic `.""" + ... + + def get_hookimpls(self) -> list[HookImpl]: + """Get all registered hook implementations for this hook.""" + ... + + def set_specification( + self, + specmodule_or_class: _Namespace, + spec_config: HookspecConfiguration | Mapping[str, Any], + ) -> None: + """Set the hook specification.""" + ... + + def __call__(self, **kwargs: object) -> Any: + """Call the hook with given kwargs.""" + ... + + def call_historic( + self, + result_callback: Callable[[Any], None] | None = None, + kwargs: Mapping[str, object] | None = None, + ) -> None: + """Call the hook historically.""" + ... + + def call_extra( + self, methods: Sequence[Callable[..., object]], kwargs: Mapping[str, object] + ) -> Any: + """Call the hook with additional methods.""" + ... + @final class HookRelay: @@ -41,7 +137,7 @@ def __init__(self) -> None: if TYPE_CHECKING: - def __getattr__(self, name: str) -> HookCaller: ... + def __getattr__(self, name: str) -> NormalHookCaller | HistoricHookCaller: ... # Historical name (pluggy<=1.2), kept for backward compatibility. @@ -53,13 +149,13 @@ def __getattr__(self, name: str) -> HookCaller: ... ] -class HookCaller: +class NormalHookCaller: """A caller of all registered implementations of a hook specification.""" __slots__ = ( - "_call_history", "_hookexec", - "_hookimpls", + "_normal_hookimpls", + "_wrapper_hookimpls", "name", "spec", ) @@ -69,26 +165,22 @@ def __init__( name: str, hook_execute: _HookExec, specmodule_or_class: _Namespace | None = None, - spec_opts: HookspecConfiguration | None = None, + spec_config: HookspecConfiguration | None = None, ) -> None: """:meta private:""" #: Name of the hook getting called. self.name: Final = name self._hookexec: Final = hook_execute - # The hookimpls list. The caller iterates it *in reverse*. Format: - # 1. trylast nonwrappers - # 2. nonwrappers - # 3. tryfirst nonwrappers - # 4. trylast wrappers - # 5. wrappers - # 6. tryfirst wrappers - self._hookimpls: Final[list[HookImpl]] = [] - self._call_history: _CallHistory | None = None + # Split hook implementations into two lists for simpler management: + # Normal hooks: [trylast, normal, tryfirst] + # Wrapper hooks: [trylast, normal, tryfirst] + self._normal_hookimpls: Final[list[NormalImpl]] = [] + self._wrapper_hookimpls: Final[list[WrapperImpl]] = [] # TODO: Document, or make private. self.spec: HookSpec | None = None if specmodule_or_class is not None: - assert spec_opts is not None - self.set_specification(specmodule_or_class, spec_opts) + assert spec_config is not None + self.set_specification(specmodule_or_class, spec_config) # TODO: Document, or make private. def has_spec(self) -> bool: @@ -98,80 +190,56 @@ def has_spec(self) -> bool: def set_specification( self, specmodule_or_class: _Namespace, - spec_opts: HookspecConfiguration, + spec_config: HookspecConfiguration | Mapping[str, Any], ) -> None: if self.spec is not None: raise ValueError( f"Hook {self.spec.name!r} is already registered " f"within namespace {self.spec.namespace}" ) - self.spec = HookSpec(specmodule_or_class, self.name, spec_opts) - if spec_opts.historic: - self._call_history = [] + config = _coerce_spec_config(spec_config) + if config.historic: + raise ValueError( + f"NormalHookCaller cannot handle historic hooks. " + f"Use HistoricHookCaller for {self.name!r}" + ) + self.spec = HookSpec(specmodule_or_class, self.name, config) def is_historic(self) -> bool: """Whether this caller is :ref:`historic `.""" - return self._call_history is not None + return False def _remove_plugin(self, plugin: _Plugin) -> None: """Remove all hook implementations registered by the given plugin.""" - remaining = [impl for impl in self._hookimpls if impl.plugin != plugin] - if len(remaining) == len(self._hookimpls): + remaining_normal = [i for i in self._normal_hookimpls if i.plugin != plugin] + remaining_wrapper = [i for i in self._wrapper_hookimpls if i.plugin != plugin] + if len(remaining_normal) == len(self._normal_hookimpls) and len( + remaining_wrapper + ) == len(self._wrapper_hookimpls): raise ValueError(f"plugin {plugin!r} not found") - self._hookimpls[:] = remaining + self._normal_hookimpls[:] = remaining_normal + self._wrapper_hookimpls[:] = remaining_wrapper def get_hookimpls(self) -> list[HookImpl]: - """Get all registered hook implementations for this hook.""" - return self._hookimpls.copy() + """Get all registered hook implementations for this hook. + + Normal implementations come first, then wrappers (matching the + historical combined-list ordering). + """ + return [*self._normal_hookimpls, *self._wrapper_hookimpls] def _add_hookimpl(self, hookimpl: HookImpl) -> None: """Add an implementation to the callback chain.""" - for i, method in enumerate(self._hookimpls): - if method.hookwrapper or method.wrapper: - splitpoint = i - break - else: - splitpoint = len(self._hookimpls) - if hookimpl.hookwrapper or hookimpl.wrapper: - start, end = splitpoint, len(self._hookimpls) - else: - start, end = 0, splitpoint - - if hookimpl.trylast: - self._hookimpls.insert(start, hookimpl) - elif hookimpl.tryfirst: - self._hookimpls.insert(end, hookimpl) + if isinstance(hookimpl, WrapperImpl): + _insert_hookimpl_into_list(hookimpl, self._wrapper_hookimpls) else: - # find last non-tryfirst method - i = end - 1 - while i >= start and self._hookimpls[i].tryfirst: - i -= 1 - self._hookimpls.insert(i + 1, hookimpl) + assert isinstance(hookimpl, NormalImpl), ( + "normal hook implementations must be NormalImpl instances" + ) + _insert_hookimpl_into_list(hookimpl, self._normal_hookimpls) def __repr__(self) -> str: - return f"" - - def _verify_all_args_are_provided(self, kwargs: Mapping[str, object]) -> None: - # This is written to avoid expensive operations when not needed. - if self.spec: - for argname in self.spec.argnames: - if argname not in kwargs: - notincall = ", ".join( - repr(argname) - for argname in self.spec.argnames - # Avoid self.spec.argnames - kwargs.keys() - # it doesn't preserve order. - if argname not in kwargs - ) - warnings.warn( - f"Argument(s) {notincall} which are declared in the hookspec " - "cannot be found in this hook call", - # 3, not 2: the warning is raised in this helper, which - # is called by __call__/call_historic/call_extra, which - # are called by the code making the hook call. - stacklevel=3, - ) - break + return f"" def __call__(self, **kwargs: object) -> Any: """Call the hook. @@ -182,13 +250,142 @@ def __call__(self, **kwargs: object) -> Any: Returns the result(s) of calling all registered plugins, see :ref:`calling`. """ - assert not self.is_historic(), ( - "Cannot directly call a historic hook - use call_historic instead." - ) - self._verify_all_args_are_provided(kwargs) + if self.spec: + self.spec.verify_all_args_are_provided(kwargs) firstresult = self.spec.config.firstresult if self.spec else False # Copy because plugins may register other plugins during iteration (#438). - return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) + return self._hookexec( + self.name, + self._normal_hookimpls.copy(), + self._wrapper_hookimpls.copy(), + kwargs, + firstresult, + ) + + def call_historic( + self, + result_callback: Callable[[Any], None] | None = None, + kwargs: Mapping[str, object] | None = None, + ) -> None: + """Historic calls are only supported by historic hooks.""" + raise AssertionError( + f"Hook {self.name!r} is not historic - cannot call call_historic" + ) + + def call_extra( + self, methods: Sequence[Callable[..., object]], kwargs: Mapping[str, object] + ) -> Any: + """Call the hook with some additional temporarily participating + methods using the specified ``kwargs`` as call parameters, see + :ref:`call_extra`.""" + if self.spec: + self.spec.verify_all_args_are_provided(kwargs) + config = HookimplConfiguration() + normal_hookimpls = self._normal_hookimpls.copy() + for method in methods: + hookimpl = config.create_hookimpl(None, "", method) + # call_extra only supports normal implementations. + assert isinstance(hookimpl, NormalImpl) + _insert_hookimpl_into_list(hookimpl, normal_hookimpls) + firstresult = self.spec.config.firstresult if self.spec else False + return self._hookexec( + self.name, + normal_hookimpls, + self._wrapper_hookimpls.copy(), + kwargs, + firstresult, + ) + + def _maybe_apply_history(self, method: HookImpl) -> None: + """Nothing to do - normal hooks have no call history.""" + + +# Historical name (pluggy<=1.2), kept for backward compatibility. +_HookCaller = NormalHookCaller + + +class HistoricHookCaller: + """A caller for historic hook specifications that memorizes and replays + calls. + + Historic hooks memorize every call and replay them on plugins registered + after the call was made. Historic hooks do not support wrappers. + """ + + __slots__ = ( + "_call_history", + "_hookexec", + "_hookimpls", + "name", + "spec", + ) + + spec: HookSpec + + def __init__( + self, + name: str, + hook_execute: _HookExec, + specmodule_or_class: _Namespace, + spec_config: HookspecConfiguration, + ) -> None: + """:meta private:""" + assert spec_config.historic, "HistoricHookCaller requires historic=True" + #: Name of the hook getting called. + self.name: Final = name + self._hookexec: Final = hook_execute + # The hookimpls list for historic hooks (no wrappers supported). + self._hookimpls: Final[list[NormalImpl]] = [] + self._call_history: Final[_CallHistory] = [] + # TODO: Document, or make private. + self.spec = HookSpec(specmodule_or_class, name, spec_config) + + def has_spec(self) -> bool: + return True + + def set_specification( + self, + specmodule_or_class: _Namespace, + spec_config: HookspecConfiguration | Mapping[str, Any], + ) -> None: + """Historic hooks cannot have their specification changed.""" + raise ValueError( + f"Hook {self.spec.name!r} is already registered " + f"within namespace {self.spec.namespace}" + ) + + def is_historic(self) -> bool: + """Whether this caller is :ref:`historic `.""" + return True + + def _remove_plugin(self, plugin: _Plugin) -> None: + remaining = [impl for impl in self._hookimpls if impl.plugin != plugin] + if len(remaining) == len(self._hookimpls): + raise ValueError(f"plugin {plugin!r} not found") + self._hookimpls[:] = remaining + + def get_hookimpls(self) -> list[HookImpl]: + """Get all registered hook implementations for this hook.""" + return list(self._hookimpls) + + def _add_hookimpl(self, hookimpl: HookImpl) -> None: + """Add an implementation to the callback chain.""" + assert isinstance(hookimpl, NormalImpl), ( + "historic hooks do not support wrappers" + ) + _insert_hookimpl_into_list(hookimpl, self._hookimpls) + + def __repr__(self) -> str: + return f"" + + def __call__(self, **kwargs: object) -> Any: + """Historic hooks cannot be called directly. + + Use :meth:`call_historic` instead. + """ + raise AssertionError( + "Cannot directly call a historic hook - use call_historic instead." + ) def call_historic( self, @@ -203,14 +400,13 @@ def call_historic( If provided, will be called for each non-``None`` result obtained from a hook implementation. """ - assert self._call_history is not None kwargs = kwargs or {} - self._verify_all_args_are_provided(kwargs) + self.spec.verify_all_args_are_provided(kwargs) self._call_history.append((kwargs, result_callback)) # Historizing hooks don't return results. # Remember firstresult isn't compatible with historic. # Copy because plugins may register other plugins during iteration (#438). - res = self._hookexec(self.name, self._hookimpls.copy(), kwargs, False) + res = self._hookexec(self.name, self._hookimpls.copy(), [], kwargs, False) if result_callback is None: return if isinstance(res, list): @@ -220,86 +416,164 @@ def call_historic( def call_extra( self, methods: Sequence[Callable[..., object]], kwargs: Mapping[str, object] ) -> Any: - """Call the hook with some additional temporarily participating - methods using the specified ``kwargs`` as call parameters, see - :ref:`call_extra`.""" - assert not self.is_historic(), ( + """Historic hooks do not support call_extra.""" + raise AssertionError( "Cannot directly call a historic hook - use call_historic instead." ) - self._verify_all_args_are_provided(kwargs) - config = HookimplConfiguration() - hookimpls = self._hookimpls.copy() - for method in methods: - hookimpl = config.create_hookimpl(None, "", method) - # Find last non-tryfirst nonwrapper method. - i = len(hookimpls) - 1 - while i >= 0 and ( - # Skip wrappers. - (hookimpls[i].hookwrapper or hookimpls[i].wrapper) - # Skip tryfirst nonwrappers. - or hookimpls[i].tryfirst - ): - i -= 1 - hookimpls.insert(i + 1, hookimpl) - firstresult = self.spec.config.firstresult if self.spec else False - return self._hookexec(self.name, hookimpls, kwargs, firstresult) def _maybe_apply_history(self, method: HookImpl) -> None: - """Apply call history to a new hookimpl if it is marked as historic.""" - if self.is_historic(): - assert self._call_history is not None - for kwargs, result_callback in self._call_history: - res = self._hookexec(self.name, [method], kwargs, False) - if res and result_callback is not None: - # XXX: remember firstresult isn't compat with historic - assert isinstance(res, list) - result_callback(res[0]) - - -# Historical name (pluggy<=1.2), kept for backward compatibility. -_HookCaller = HookCaller - - -class _SubsetHookCaller(HookCaller): - """A proxy to another HookCaller which manages calls to all registered + """Apply call history to a new hookimpl.""" + assert isinstance(method, NormalImpl) + for kwargs, result_callback in self._call_history: + res = self._hookexec(self.name, [method], [], kwargs, False) + if res and result_callback is not None: + # XXX: remember firstresult isn't compat with historic + assert isinstance(res, list) + result_callback(res[0]) + + +class SubsetHookCaller: + """A proxy to another hook caller which manages calls to all registered plugins except the ones from remove_plugins.""" - # This class is unusual: in inhertits from `HookCaller` so all of - # the *code* runs in the class, but it delegates all underlying *data* - # to the original HookCaller. # `subset_hook_caller` used to be implemented by creating a full-fledged # HookCaller, copying all hookimpls from the original. This had problems # with memory leaks (#346) and historic calls (#347), which make a proxy # approach better. - # An alternative implementation is to use a `_getattr__`/`__getattribute__` - # proxy, however that adds more overhead and is more tricky to implement. __slots__ = ( "_orig", "_remove_plugins", ) - def __init__(self, orig: HookCaller, remove_plugins: AbstractSet[_Plugin]) -> None: - self._orig = orig - self._remove_plugins = remove_plugins - self.name = orig.name # type: ignore[misc] - self._hookexec = orig._hookexec # type: ignore[misc] + def __init__( + self, + orig: NormalHookCaller | HistoricHookCaller, + remove_plugins: AbstractSet[_Plugin], + ) -> None: + """:meta private:""" + self._orig: Final = orig + self._remove_plugins: Final = remove_plugins - @property # type: ignore[misc] - def _hookimpls(self) -> list[HookImpl]: - return [ - impl - for impl in self._orig._hookimpls - if impl.plugin not in self._remove_plugins - ] + @property + def name(self) -> str: + return self._orig.name @property - def spec(self) -> HookSpec | None: # type: ignore[override] + def spec(self) -> HookSpec | None: return self._orig.spec - @property - def _call_history(self) -> _CallHistory | None: # type: ignore[override] - return self._orig._call_history + def has_spec(self) -> bool: + return self._orig.has_spec() + + def is_historic(self) -> bool: + return self._orig.is_historic() + + def _get_filtered(self, hookimpls: Sequence[_T_HookImpl]) -> list[_T_HookImpl]: + """Filter out hook implementations from removed plugins.""" + return [impl for impl in hookimpls if impl.plugin not in self._remove_plugins] + + def get_hookimpls(self) -> list[HookImpl]: + """Get filtered hook implementations for this hook.""" + return self._get_filtered(self._orig.get_hookimpls()) + + def set_specification( + self, + specmodule_or_class: _Namespace, + spec_config: HookspecConfiguration | Mapping[str, Any], + ) -> None: + """SubsetHookCaller is a read-only proxy - specs cannot be set.""" + raise RuntimeError( + f"Cannot set specification on SubsetHookCaller {self.name!r} - " + "it is a read-only proxy to another hook caller" + ) + + def __call__(self, **kwargs: object) -> Any: + """Call the hook with filtered implementations.""" + if self.is_historic(): + raise AssertionError( + "Cannot directly call a historic hook - use call_historic instead." + ) + orig = self._orig + assert isinstance(orig, NormalHookCaller) + if orig.spec: + orig.spec.verify_all_args_are_provided(kwargs) + firstresult = orig.spec.config.firstresult if orig.spec else False + return orig._hookexec( + self.name, + self._get_filtered(orig._normal_hookimpls), + self._get_filtered(orig._wrapper_hookimpls), + kwargs, + firstresult, + ) + + def call_historic( + self, + result_callback: Callable[[Any], None] | None = None, + kwargs: Mapping[str, object] | None = None, + ) -> None: + """Call the hook with given ``kwargs`` for all registered plugins and + for all plugins which will be registered afterwards, see + :ref:`historic`. + """ + orig = self._orig + assert isinstance(orig, HistoricHookCaller), ( + f"Hook {self.name!r} is not historic - cannot call call_historic" + ) + kwargs = kwargs or {} + orig.spec.verify_all_args_are_provided(kwargs) + # History is shared with the original caller. + orig._call_history.append((kwargs, result_callback)) + res = orig._hookexec( + self.name, self._get_filtered(orig._hookimpls), [], kwargs, False + ) + if result_callback is None: + return + if isinstance(res, list): + for x in res: + result_callback(x) + + def call_extra( + self, methods: Sequence[Callable[..., object]], kwargs: Mapping[str, object] + ) -> Any: + """Call the hook with some additional temporarily participating + methods using the specified ``kwargs`` as call parameters, see + :ref:`call_extra`.""" + orig = self._orig + if self.is_historic(): + raise AssertionError( + "Cannot directly call a historic hook - use call_historic instead." + ) + assert isinstance(orig, NormalHookCaller) + if orig.spec: + orig.spec.verify_all_args_are_provided(kwargs) + config = HookimplConfiguration() + normal_impls = self._get_filtered(orig._normal_hookimpls) + for method in methods: + hookimpl = config.create_hookimpl(None, "", method) + assert isinstance(hookimpl, NormalImpl) + _insert_hookimpl_into_list(hookimpl, normal_impls) + firstresult = orig.spec.config.firstresult if orig.spec else False + return orig._hookexec( + self.name, + normal_impls, + self._get_filtered(orig._wrapper_hookimpls), + kwargs, + firstresult, + ) def __repr__(self) -> str: - return f"<_SubsetHookCaller {self.name!r}>" + return f"" + + +# Historical name, kept for backward compatibility. +_SubsetHookCaller = SubsetHookCaller + + +if TYPE_CHECKING: + # Verify the concrete callers satisfy the HookCaller protocol. + _: list[HookCaller] = [ + cast(NormalHookCaller, None), + cast(HistoricHookCaller, None), + cast(SubsetHookCaller, None), + ] diff --git a/src/pluggy/_decorators.py b/src/pluggy/_decorators.py index 0c80e3fb..cf135a3f 100644 --- a/src/pluggy/_decorators.py +++ b/src/pluggy/_decorators.py @@ -360,3 +360,26 @@ def opts(self) -> HookspecConfiguration: Use :attr:`config` instead. """ return self.config + + def verify_all_args_are_provided(self, kwargs: Mapping[str, object]) -> None: + """Warn if a hook call does not provide all declared arguments.""" + # This is written to avoid expensive operations when not needed. + for argname in self.argnames: + if argname not in kwargs: + notincall = ", ".join( + repr(argname) + for argname in self.argnames + # Avoid self.argnames - kwargs.keys() + # it doesn't preserve order. + if argname not in kwargs + ) + warnings.warn( + f"Argument(s) {notincall} which are declared in the hookspec " + "cannot be found in this hook call", + # 3, not 2: the warning is raised here, in the spec, which + # every caller invokes directly from __call__/ + # call_historic/call_extra, which the calling code invokes. + # Adding a hop between those two breaks this. + stacklevel=3, + ) + break diff --git a/src/pluggy/_execution.py b/src/pluggy/_execution.py index 12a03b76..faf02d98 100644 --- a/src/pluggy/_execution.py +++ b/src/pluggy/_execution.py @@ -13,7 +13,9 @@ from typing import TypeAlias import warnings -from ._impl import HookImpl +from ._impl import CompletionHook +from ._impl import NormalImpl +from ._impl import WrapperImpl from ._result import Result from ._warnings import PluggyTeardownRaisedWarning @@ -24,7 +26,7 @@ def run_old_style_hookwrapper( - hook_impl: HookImpl, hook_name: str, args: Sequence[object] + hook_impl: WrapperImpl, hook_name: str, args: Sequence[object] ) -> Teardown: """ backward compatibility wrapper to run a old style hookwrapper as a wrapper @@ -67,7 +69,7 @@ def _raise_wrapfail( def _warn_teardown_exception( - hook_name: str, hook_impl: HookImpl, e: BaseException + hook_name: str, hook_impl: WrapperImpl, e: BaseException ) -> None: msg = ( f"A plugin raised an exception during an old-style hookwrapper teardown.\n" @@ -75,12 +77,13 @@ def _warn_teardown_exception( f"{type(e).__name__}: {e}\n" f"For more information see https://pluggy.readthedocs.io/en/stable/api_reference.html#pluggy.PluggyTeardownRaisedWarning" ) - warnings.warn(PluggyTeardownRaisedWarning(msg), stacklevel=6) + warnings.warn(PluggyTeardownRaisedWarning(msg), stacklevel=7) def _multicall( hook_name: str, - hook_impls: Sequence[HookImpl], + normal_impls: Sequence[NormalImpl], + wrapper_impls: Sequence[WrapperImpl], caller_kwargs: Mapping[str, object], firstresult: bool, ) -> object | list[object]: @@ -88,79 +91,48 @@ def _multicall( result(s). ``caller_kwargs`` comes from HookCaller.__call__(). + + Wrappers own their setup/teardown via + :meth:`~pluggy._impl.WrapperImpl.setup_and_get_completion_hook`; + this function only orchestrates the phases: + + 1. Set up wrappers, collecting their completion hooks. + 2. Run normal implementations. + 3. Run completion hooks LIFO, each may replace ``(result, exception)``. + 4. Raise or return. """ __tracebackhide__ = True results: list[object] = [] - exception = None - teardowns: list[Teardown] = [] - try: # run impl and wrapper setup functions in a loop - for hook_impl in reversed(hook_impls): - args = hook_impl._get_call_args(caller_kwargs) - - if hook_impl.hookwrapper: - function_gen = run_old_style_hookwrapper(hook_impl, hook_name, args) - - next(function_gen) # first yield - teardowns.append(function_gen) - - elif hook_impl.wrapper: - res = hook_impl.function(*args) - # If this cast is not valid, a type error is raised below, - # which is the desired response. - if TYPE_CHECKING: - function_gen = cast(Generator[None, object, object], res) - else: - function_gen = res - try: - next(function_gen) # first yield - except StopIteration: - _raise_wrapfail(function_gen, "did not yield") - teardowns.append(function_gen) - else: - res = hook_impl.function(*args) - if res is not None: - results.append(res) - if firstresult: # halt further impl calls - break + exception: BaseException | None = None + completion_hooks: list[CompletionHook] = [] + try: + # Set up all wrappers and collect their completion hooks. + for wrapper_impl in reversed(wrapper_impls): + completion_hooks.append( + wrapper_impl.setup_and_get_completion_hook(hook_name, caller_kwargs) + ) + + # Run normal implementations. + for normal_impl in reversed(normal_impls): + args = normal_impl._get_call_args(caller_kwargs) + res = normal_impl.function(*args) + if res is not None: + results.append(res) + if firstresult: # halt further impl calls + break except BaseException as exc: exception = exc - finally: - if firstresult: # first result hooks return a single value - result = results[0] if results else None - else: - result = results - - # run all wrapper post-yield blocks - for teardown in reversed(teardowns): - try: - if exception is not None: - try: - teardown.throw(exception) - except RuntimeError as re: - # StopIteration from generator causes RuntimeError - # even for coroutine usage - see #544 - if ( - isinstance(exception, StopIteration) - and re.__cause__ is exception - ): - teardown.close() - continue - else: - raise - else: - teardown.send(result) - # Following is unreachable for a well behaved hook wrapper. - # Try to force finalizers otherwise postponed till GC action. - # Note: close() may raise if generator handles GeneratorExit. - teardown.close() - except StopIteration as si: - result = si.value - exception = None - continue - except BaseException as e: - exception = e - continue - _raise_wrapfail(teardown, "has second yield") + + result: object | list[object] | None + if firstresult: # first result hooks return a single value + result = results[0] if results else None + else: + result = results + + # Run completion hooks in reverse order (LIFO); each may replace the + # current (result, exception) outcome. + for completion_hook in reversed(completion_hooks): + result, exception = completion_hook(result, exception) if exception is not None: raise exception diff --git a/src/pluggy/_hooks.py b/src/pluggy/_hooks.py index ef3a76f9..3b659b8d 100644 --- a/src/pluggy/_hooks.py +++ b/src/pluggy/_hooks.py @@ -11,8 +11,11 @@ from ._caller import _HookExec from ._caller import _HookRelay from ._caller import _SubsetHookCaller +from ._caller import HistoricHookCaller from ._caller import HookCaller from ._caller import HookRelay +from ._caller import NormalHookCaller +from ._caller import SubsetHookCaller from ._config import HookimplConfiguration from ._config import HookspecConfiguration from ._decorators import _Namespace @@ -30,6 +33,7 @@ __all__ = [ "CompletionHook", + "HistoricHookCaller", "HookCaller", "HookImpl", "HookRelay", @@ -38,7 +42,9 @@ "HookimplMarker", "HookspecConfiguration", "HookspecMarker", + "NormalHookCaller", "NormalImpl", + "SubsetHookCaller", "WrapperImpl", "_HookCaller", "_HookExec", diff --git a/src/pluggy/_manager.py b/src/pluggy/_manager.py index 859f2462..fb2a3f6e 100644 --- a/src/pluggy/_manager.py +++ b/src/pluggy/_manager.py @@ -24,10 +24,14 @@ from ._hooks import _HookImplFunction from ._hooks import _Namespace from ._hooks import _Plugin -from ._hooks import _SubsetHookCaller +from ._hooks import HistoricHookCaller from ._hooks import HookCaller from ._hooks import HookImpl from ._hooks import HookRelay +from ._hooks import NormalHookCaller +from ._hooks import NormalImpl +from ._hooks import SubsetHookCaller +from ._hooks import WrapperImpl from ._pytest_compat import HookimplOpts from ._pytest_compat import HookspecOpts from ._result import Result @@ -183,13 +187,16 @@ def __init__(self, project_name: str) -> None: def _hookexec( self, hook_name: str, - methods: Sequence[HookImpl], - kwargs: Mapping[str, object], + normal_impls: Sequence[NormalImpl], + wrapper_impls: Sequence[WrapperImpl], + caller_kwargs: Mapping[str, object], firstresult: bool, ) -> object | list[object]: # called from all hookcaller instances. # enable_tracing will set its own wrapping function at self._inner_hookexec - return self._inner_hookexec(hook_name, methods, kwargs, firstresult) + return self._inner_hookexec( + hook_name, normal_impls, wrapper_impls, caller_kwargs, firstresult + ) def register(self, plugin: _Plugin, name: str | None = None) -> str | None: """Register a plugin and return its name. @@ -237,9 +244,11 @@ def register(self, plugin: _Plugin, name: str | None = None) -> str | None: method: _HookImplFunction[object] = found[1] hookimpl = hookimpl_config.create_hookimpl(plugin, plugin_name, method) hook_name = hookimpl_config.specname or attr_name - hook: HookCaller | None = getattr(self.hook, hook_name, None) + hook: NormalHookCaller | HistoricHookCaller | None = getattr( + self.hook, hook_name, None + ) if hook is None: - hook = HookCaller(hook_name, self._hookexec) + hook = NormalHookCaller(hook_name, self._hookexec) setattr(self.hook, hook_name, hook) elif hook.has_spec(): self._verify_hook(hook, hookimpl) @@ -323,6 +332,7 @@ def unregister( hookcallers = self.get_hookcallers(plugin) if hookcallers: for hookcaller in hookcallers: + assert isinstance(hookcaller, (NormalHookCaller, HistoricHookCaller)) hookcaller._remove_plugin(plugin) # if self._name2plugin[name] == None registration was blocked: ignore @@ -361,10 +371,36 @@ def add_hookspecs(self, module_or_class: _Namespace) -> None: for name in dir(module_or_class): spec_config = self._discover_hookspec_configuration(module_or_class, name) if spec_config is not None: - hc: HookCaller | None = getattr(self.hook, name, None) + hc: NormalHookCaller | HistoricHookCaller | None = getattr( + self.hook, name, None + ) if hc is None: - hc = HookCaller(name, self._hookexec, module_or_class, spec_config) + if spec_config.historic: + hc = HistoricHookCaller( + name, self._hookexec, module_or_class, spec_config + ) + else: + hc = NormalHookCaller( + name, self._hookexec, module_or_class, spec_config + ) setattr(self.hook, name, hc) + elif spec_config.historic and not hc.is_historic(): + # Plugins registered this hook before the historic spec was + # known - hand the implementations over to a + # HistoricHookCaller. + assert isinstance(hc, NormalHookCaller) + if hc.has_spec(): + # Let set_specification raise the usual error. + hc.set_specification(module_or_class, spec_config) + raise AssertionError("unreachable") # pragma: no cover + old_hookimpls = hc.get_hookimpls() + historic_hc = HistoricHookCaller( + name, self._hookexec, module_or_class, spec_config + ) + setattr(self.hook, name, historic_hc) + for hookimpl in old_hookimpls: + self._verify_hook(historic_hc, hookimpl) + historic_hc._add_hookimpl(hookimpl) else: # Plugins registered this hook without knowing the spec. hc.set_specification(module_or_class, spec_config) @@ -522,7 +558,7 @@ def check_pending(self) -> None: for name in self.hook.__dict__: if name[0] == "_": continue - hook: HookCaller = getattr(self.hook, name) + hook: NormalHookCaller | HistoricHookCaller = getattr(self.hook, name) if not hook.has_spec(): for hookimpl in hook.get_hookimpls(): if not hookimpl.optionalhook: @@ -623,13 +659,19 @@ def add_hookcall_monitoring( def traced_hookexec( hook_name: str, - hook_impls: Sequence[HookImpl], + normal_impls: Sequence[NormalImpl], + wrapper_impls: Sequence[WrapperImpl], caller_kwargs: Mapping[str, object], firstresult: bool, ) -> object | list[object]: + # For backward compatibility of the before/after callback shapes, + # combine the split lists into one. + hook_impls: list[HookImpl] = [*normal_impls, *wrapper_impls] before(hook_name, hook_impls, caller_kwargs) outcome = Result.from_call( - lambda: oldcall(hook_name, hook_impls, caller_kwargs, firstresult) + lambda: oldcall( + hook_name, normal_impls, wrapper_impls, caller_kwargs, firstresult + ) ) after(outcome, hook_name, hook_impls, caller_kwargs) return outcome.get_result() @@ -671,18 +713,18 @@ def subset_hook_caller( ) -> HookCaller: """Return a proxy :class:`~pluggy.HookCaller` for the named hook which calls all registered plugins except the ones from remove_plugins.""" - orig: HookCaller = getattr(self.hook, name) + orig: NormalHookCaller | HistoricHookCaller = getattr(self.hook, name) plugins_to_remove = set(remove_plugins) # Optimization: discard plugins to remove which don't actually implement # the hook, to make checks faster. plugins_to_remove.intersection_update( - hookimpl.plugin for hookimpl in orig._hookimpls + hookimpl.plugin for hookimpl in orig.get_hookimpls() ) # Optimization: if none of the plugins to remove actually implement the # hook, avoid the subset hook caller overhead. if not plugins_to_remove: return orig - return _SubsetHookCaller(orig, plugins_to_remove) + return SubsetHookCaller(orig, plugins_to_remove) def _formatdef(func: Callable[..., object]) -> str: diff --git a/testing/benchmark.py b/testing/benchmark.py index 0ca52ad2..4efbf080 100644 --- a/testing/benchmark.py +++ b/testing/benchmark.py @@ -11,8 +11,8 @@ from pluggy import HookimplMarker from pluggy import HookspecMarker from pluggy import PluginManager +from pluggy import WrapperImpl from pluggy._callers import _multicall -from pluggy._hooks import HookImpl from pluggy._hooks import varnames @@ -104,13 +104,17 @@ def wrappers(request: Any) -> list[object]: def test_hook_and_wrappers_speed(benchmark, hooks, wrappers) -> None: def setup(): hook_name = "foo" - hook_impls = [] + normal_impls = [] + wrapper_impls = [] for method in hooks + wrappers: - f = HookImpl(None, "", method, method.example_impl) - hook_impls.append(f) + f = method.example_impl.create_hookimpl(None, "", method) + if isinstance(f, WrapperImpl): + wrapper_impls.append(f) + else: + normal_impls.append(f) caller_kwargs = {"arg1": 1, "arg2": 2, "arg3": 3} firstresult = False - return (hook_name, hook_impls, caller_kwargs, firstresult), {} + return (hook_name, normal_impls, wrapper_impls, caller_kwargs, firstresult), {} benchmark.pedantic(_multicall, setup=setup, rounds=10) diff --git a/testing/test_hookcaller.py b/testing/test_hookcaller.py index 49b01e5b..18b1f00d 100644 --- a/testing/test_hookcaller.py +++ b/testing/test_hookcaller.py @@ -5,11 +5,14 @@ import pytest +from pluggy import HistoricHookCaller +from pluggy import HookCaller from pluggy import HookimplMarker +from pluggy import HookspecConfiguration from pluggy import HookspecMarker +from pluggy import NormalHookCaller from pluggy import PluginManager from pluggy import PluginValidationError -from pluggy._hooks import HookCaller from pluggy._hooks import HookImpl @@ -18,21 +21,23 @@ @pytest.fixture -def hc(pm: PluginManager) -> HookCaller: +def hc(pm: PluginManager) -> NormalHookCaller: class Hooks: @hookspec def he_method1(self, arg: object) -> None: pass pm.add_hookspecs(Hooks) - return pm.hook.he_method1 + hc = pm.hook.he_method1 + assert isinstance(hc, NormalHookCaller) + return hc FuncT = TypeVar("FuncT", bound=Callable[..., object]) class AddMeth: - def __init__(self, hc: HookCaller) -> None: + def __init__(self, hc: NormalHookCaller) -> None: self.hc = hc def __call__( @@ -49,16 +54,15 @@ def wrap(func: FuncT) -> FuncT: hookwrapper=hookwrapper, wrapper=wrapper, )(func) - self.hc._add_hookimpl( - HookImpl(None, "", func, func.example_impl), # type: ignore[attr-defined] - ) + config = func.example_impl # type: ignore[attr-defined] + self.hc._add_hookimpl(config.create_hookimpl(None, "", func)) return func return wrap @pytest.fixture -def addmeth(hc: HookCaller) -> AddMeth: +def addmeth(hc: NormalHookCaller) -> AddMeth: return AddMeth(hc) @@ -66,7 +70,7 @@ def funcs(hookmethods: Sequence[HookImpl]) -> list[Callable[..., object]]: return [hookmethod.function for hookmethod in hookmethods] -def test_adding_nonwrappers(hc: HookCaller, addmeth: AddMeth) -> None: +def test_adding_nonwrappers(hc: NormalHookCaller, addmeth: AddMeth) -> None: @addmeth() def he_method1() -> None: pass @@ -82,7 +86,7 @@ def he_method3() -> None: assert funcs(hc.get_hookimpls()) == [he_method1, he_method2, he_method3] -def test_adding_nonwrappers_trylast(hc: HookCaller, addmeth: AddMeth) -> None: +def test_adding_nonwrappers_trylast(hc: NormalHookCaller, addmeth: AddMeth) -> None: @addmeth() def he_method1_middle() -> None: pass @@ -98,7 +102,7 @@ def he_method1_b() -> None: assert funcs(hc.get_hookimpls()) == [he_method1, he_method1_middle, he_method1_b] -def test_adding_nonwrappers_trylast3(hc: HookCaller, addmeth: AddMeth) -> None: +def test_adding_nonwrappers_trylast3(hc: NormalHookCaller, addmeth: AddMeth) -> None: @addmeth() def he_method1_a() -> None: pass @@ -123,7 +127,7 @@ def he_method1_d() -> None: ] -def test_adding_nonwrappers_trylast2(hc: HookCaller, addmeth: AddMeth) -> None: +def test_adding_nonwrappers_trylast2(hc: NormalHookCaller, addmeth: AddMeth) -> None: @addmeth() def he_method1_middle() -> None: pass @@ -139,7 +143,7 @@ def he_method1() -> None: assert funcs(hc.get_hookimpls()) == [he_method1, he_method1_middle, he_method1_b] -def test_adding_nonwrappers_tryfirst(hc: HookCaller, addmeth: AddMeth) -> None: +def test_adding_nonwrappers_tryfirst(hc: NormalHookCaller, addmeth: AddMeth) -> None: @addmeth(tryfirst=True) def he_method1() -> None: pass @@ -155,7 +159,7 @@ def he_method1_b() -> None: assert funcs(hc.get_hookimpls()) == [he_method1_middle, he_method1_b, he_method1] -def test_adding_wrappers_ordering(hc: HookCaller, addmeth: AddMeth) -> None: +def test_adding_wrappers_ordering(hc: NormalHookCaller, addmeth: AddMeth) -> None: @addmeth(hookwrapper=True) def he_method1(): yield # pragma: no cover @@ -185,7 +189,9 @@ def he_method3(): ] -def test_adding_wrappers_ordering_tryfirst(hc: HookCaller, addmeth: AddMeth) -> None: +def test_adding_wrappers_ordering_tryfirst( + hc: NormalHookCaller, addmeth: AddMeth +) -> None: @addmeth(hookwrapper=True, tryfirst=True) def he_method1(): yield # pragma: no cover @@ -201,7 +207,7 @@ def he_method3(): assert funcs(hc.get_hookimpls()) == [he_method2, he_method1, he_method3] -def test_adding_wrappers_complex(hc: HookCaller, addmeth: AddMeth) -> None: +def test_adding_wrappers_complex(hc: NormalHookCaller, addmeth: AddMeth) -> None: assert funcs(hc.get_hookimpls()) == [] @addmeth(hookwrapper=True, trylast=True) @@ -442,7 +448,7 @@ def conflict(self) -> None: ) -def test_call_extra_hook_order(hc: HookCaller, addmeth: AddMeth) -> None: +def test_call_extra_hook_order(hc: NormalHookCaller, addmeth: AddMeth) -> None: """Ensure that call_extra is calling hooks in the right order.""" order = [] @@ -513,7 +519,9 @@ def extra2() -> str: ] -def test_remove_plugin_not_found_raises(hc: HookCaller, pm: PluginManager) -> None: +def test_remove_plugin_not_found_raises( + hc: NormalHookCaller, pm: PluginManager +) -> None: """_remove_plugin() raises ValueError for a plugin that never registered an implementation on this particular hook caller.""" @@ -533,3 +541,83 @@ def he_method1(self, arg): # the failed removal must not have touched the existing registration assert len(hc.get_hookimpls()) == 1 pm.unregister(plugin) + + +def test_hookcaller_is_runtime_checkable_protocol(pm: PluginManager) -> None: + class Hooks: + @hookspec + def he_method1(self, arg: object) -> None: + pass + + @hookspec(historic=True) + def he_history(self, arg: object) -> None: + pass + + class Plugin: + @hookimpl + def he_method1(self, arg: object) -> object: + return arg + + pm.add_hookspecs(Hooks) + pm.register(Plugin()) + + normal = pm.hook.he_method1 + historic = pm.hook.he_history + subset = pm.subset_hook_caller("he_method1", []) + + assert isinstance(normal, NormalHookCaller) + assert isinstance(historic, HistoricHookCaller) + for caller in (normal, historic, subset): + assert isinstance(caller, HookCaller) + + assert not normal.is_historic() + assert historic.is_historic() + + +def test_historic_spec_after_registration_hands_over(pm: PluginManager) -> None: + """Impls registered before a historic spec move to a HistoricHookCaller.""" + out: list[object] = [] + + class Plugin: + @hookimpl + def he_history(self, arg: object) -> object: + out.append(arg) + return arg + + pm.register(Plugin()) + pre_spec_caller = pm.hook.he_history + assert isinstance(pre_spec_caller, NormalHookCaller) + + class Hooks: + @hookspec(historic=True) + def he_history(self, arg: object) -> None: + pass + + pm.add_hookspecs(Hooks) + hc = pm.hook.he_history + assert isinstance(hc, HistoricHookCaller) + assert len(hc.get_hookimpls()) == 1 + + hc.call_historic(kwargs={"arg": 1}) + assert out == [1] + + +def test_historic_rejects_direct_call_and_call_extra(pm: PluginManager) -> None: + class Hooks: + @hookspec(historic=True) + def he_history(self, arg: object) -> None: + pass + + pm.add_hookspecs(Hooks) + hc = pm.hook.he_history + with pytest.raises(AssertionError, match="use call_historic"): + hc(arg=1) + with pytest.raises(AssertionError, match="use call_historic"): + hc.call_extra([], {"arg": 1}) + with pytest.raises(ValueError, match="already registered"): + hc.set_specification(Hooks, HookspecConfiguration(historic=True)) + + +def test_normal_caller_rejects_call_historic(hc: NormalHookCaller) -> None: + with pytest.raises(AssertionError, match="not historic"): + hc.call_historic(kwargs={"arg": 1}) diff --git a/testing/test_multicall.py b/testing/test_multicall.py index e400e85a..18a5213f 100644 --- a/testing/test_multicall.py +++ b/testing/test_multicall.py @@ -7,8 +7,9 @@ from pluggy import HookCallError from pluggy import HookimplMarker from pluggy import HookspecMarker +from pluggy import NormalImpl +from pluggy import WrapperImpl from pluggy._callers import _multicall -from pluggy._hooks import HookImpl hookspec = HookspecMarker("example") @@ -20,12 +21,16 @@ def MC( kwargs: Mapping[str, object], firstresult: bool = False, ) -> object | list[object]: - caller = _multicall - hookfuncs = [] + normal_impls: list[NormalImpl] = [] + wrapper_impls: list[WrapperImpl] = [] for method in methods: - f = HookImpl(None, "", method, method.example_impl) # type: ignore[attr-defined] - hookfuncs.append(f) - return caller("foo", hookfuncs, kwargs, firstresult) + config = method.example_impl # type: ignore[attr-defined] + f = config.create_hookimpl(None, "", method) + if isinstance(f, WrapperImpl): + wrapper_impls.append(f) + else: + normal_impls.append(f) + return _multicall("foo", normal_impls, wrapper_impls, kwargs, firstresult) def test_keyword_args() -> None: diff --git a/testing/test_pluginmanager.py b/testing/test_pluginmanager.py index c35d6863..2857597c 100644 --- a/testing/test_pluginmanager.py +++ b/testing/test_pluginmanager.py @@ -705,7 +705,7 @@ class PluginNo: pm.hook.he_method1(arg=1) assert out == [10] - assert repr(hc) == "<_SubsetHookCaller 'he_method1'>" + assert repr(hc) == "" def test_subset_hook_caller_with_specname(pm: PluginManager) -> None: