From fd4fd712f591a986f0a91321985f494deaf4cdca Mon Sep 17 00:00:00 2001 From: HocVoNgThai <161827816+HocVoNgThai@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:02:40 +0700 Subject: [PATCH 1/2] Fix argument forwarding to partial callbacks --- src/pluggy/_decorators.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/pluggy/_decorators.py b/src/pluggy/_decorators.py index c5574a67..93ff4e5a 100644 --- a/src/pluggy/_decorators.py +++ b/src/pluggy/_decorators.py @@ -6,6 +6,7 @@ from collections.abc import Callable from collections.abc import Mapping +from functools import partial import inspect import sys import types @@ -261,6 +262,26 @@ def varnames( When the function looks like a class method but has no implicit first parameter, a :class:`DeprecationWarning` is emitted. """ + if isinstance(func, partial): + try: + parameters = inspect.signature( + func, follow_wrapped=False + ).parameters.values() + except (TypeError, ValueError): + return (), () + partial_args = [] + partial_kwargs = [] + for parameter in parameters: + if parameter.kind in ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ): + if parameter.default is inspect.Parameter.empty: + partial_args.append(parameter.name) + else: + partial_kwargs.append(parameter.name) + return tuple(partial_args), tuple(partial_kwargs) + is_bound = False if inspect.isclass(func): try: From 73d51663b7d560079492f4e0cf0cd86a141ad061 Mon Sep 17 00:00:00 2001 From: HocVoNgThai <161827816+HocVoNgThai@users.noreply.github.com> Date: Mon, 2 Nov 2026 14:23:54 +0700 Subject: [PATCH 2/2] fix: handle callback signatures without Python code --- changelog/817.bugfix.rst | 1 + src/pluggy/_decorators.py | 62 ++++++++++++++++---------- src/pluggy/_impl.py | 4 +- testing/test_helpers.py | 82 +++++++++++++++++++++++++++++++++++ testing/test_pluginmanager.py | 71 ++++++++++++++++++++++++++++++ 5 files changed, 195 insertions(+), 25 deletions(-) create mode 100644 changelog/817.bugfix.rst diff --git a/changelog/817.bugfix.rst b/changelog/817.bugfix.rst new file mode 100644 index 00000000..b3e86857 --- /dev/null +++ b/changelog/817.bugfix.rst @@ -0,0 +1 @@ +Fix argument forwarding to partially bound and other inspectable callbacks passed to ``HookCaller.call_extra()``, including wrapped functions and parameters made keyword-only by a partial. diff --git a/src/pluggy/_decorators.py b/src/pluggy/_decorators.py index 93ff4e5a..09fffe44 100644 --- a/src/pluggy/_decorators.py +++ b/src/pluggy/_decorators.py @@ -255,33 +255,14 @@ def varnames( 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. + Keyword-only parameters are included only for the signature fallback. :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. """ - if isinstance(func, partial): - try: - parameters = inspect.signature( - func, follow_wrapped=False - ).parameters.values() - except (TypeError, ValueError): - return (), () - partial_args = [] - partial_kwargs = [] - for parameter in parameters: - if parameter.kind in ( - inspect.Parameter.POSITIONAL_ONLY, - inspect.Parameter.POSITIONAL_OR_KEYWORD, - ): - if parameter.default is inspect.Parameter.empty: - partial_args.append(parameter.name) - else: - partial_kwargs.append(parameter.name) - return tuple(partial_args), tuple(partial_kwargs) - + original = func is_bound = False if inspect.isclass(func): try: @@ -300,6 +281,8 @@ def varnames( # Track bound methods before unwrapping, since __func__ loses that info. if inspect.ismethod(func): is_bound = True + if not hasattr(func, "__code__"): + return _varnames_from_signature(original) func = inspect.unwrap(func) # type: ignore[arg-type] if inspect.ismethod(func): is_bound = True @@ -309,8 +292,8 @@ def varnames( 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 (), () + except AttributeError: + return _varnames_from_signature(original) # Get positional argument names (positional-only + positional-or-keyword) args: tuple[str, ...] = code.co_varnames[: code.co_argcount] @@ -346,6 +329,39 @@ def varnames( return args, kwargs +def _varnames_from_signature(func: object) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Inspect callables whose implementation has no Python code object.""" + if ( + isinstance(func, partial) + and hasattr(func, "__wrapped__") + and not hasattr(func, "__signature__") + ): + # Metadata on the partial must not hide its bound arguments. The + # wrapped function itself still follows normal decorator unwrapping. + func = partial(func.func, *func.args, **func.keywords) + if sys.version_info >= (3, 14): + from annotationlib import Format + + signature = inspect.signature(func, annotation_format=Format.STRING) # type: ignore[arg-type] + else: + signature = inspect.signature(func) # type: ignore[arg-type] + parameters = signature.parameters.values() + args = [] + kwargs = [] + for parameter in parameters: + if parameter.kind in ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ): + if parameter.default is inspect.Parameter.empty: + args.append(parameter.name) + else: + kwargs.append(parameter.name) + elif parameter.kind is inspect.Parameter.KEYWORD_ONLY: + kwargs.append(parameter.name) + return tuple(args), tuple(kwargs) + + @final class HookSpec: __slots__ = ( diff --git a/src/pluggy/_impl.py b/src/pluggy/_impl.py index 1b7182f1..0f71fdac 100644 --- a/src/pluggy/_impl.py +++ b/src/pluggy/_impl.py @@ -53,8 +53,8 @@ def __init__( argnames, kwargnames = varnames(self.function) #: The positional parameter names of ``function``. self.argnames: Final = argnames - #: The keyword parameter names of ``function`` which declare defaults. - #: Keyword-only parameters are *not* included. + #: Parameters passed by keyword: defaulted positional parameters and + #: keyword-only parameters discovered by the signature fallback. self.kwargnames: Final = kwargnames #: The plugin which defined this hook implementation. self.plugin: Final = plugin diff --git a/testing/test_helpers.py b/testing/test_helpers.py index 3c58ecee..1f783fb3 100644 --- a/testing/test_helpers.py +++ b/testing/test_helpers.py @@ -1,9 +1,14 @@ from collections.abc import Callable +from functools import partial +from functools import update_wrapper from functools import wraps +import sys from typing import Any from typing import cast from typing import TypeVar +import pytest + from pluggy._hooks import varnames from pluggy._manager import _formatdef @@ -272,3 +277,80 @@ def func_with_bad_annotation( pass assert varnames(func_with_bad_annotation) == (("x", "y"), ()) + + +@pytest.mark.parametrize("binding", ["positional", "keyword"]) +def test_varnames_partial(binding) -> None: + def callback(ctx: str, value: int, flag: bool = False) -> None: + pass + + expected: tuple[tuple[str, ...], tuple[str, ...]] + if binding == "positional": + function = partial(callback, "c") + expected = (("value",), ("flag",)) + else: + function = partial(callback, ctx="c") + expected = ((), ("ctx", "value", "flag")) + assert varnames(function) == expected + + +def test_varnames_partial_middle_keyword() -> None: + def callback(value, ctx, other): + pass + + assert varnames(partial(callback, ctx="c")) == (("value",), ("ctx", "other")) + + +def test_varnames_partial_decorator() -> None: + def callback(ctx: str, value: int, flag: bool = False) -> None: + pass + + @wraps(callback) + def decorated(*args, **kwargs): + return callback(*args, **kwargs) + + assert varnames(partial(decorated, "c")) == (("value",), ("flag",)) + assert varnames(partial(decorated, ctx="c")) == ((), ("ctx", "value", "flag")) + + +def test_varnames_partial_wrapper_metadata() -> None: + def callback(ctx: str, value: int, flag: bool = False) -> None: + pass + + function = update_wrapper(partial(callback, "c"), callback) + assert varnames(function) == (("value",), ("flag",)) + + +def test_varnames_partial_bound_method() -> None: + class Callback: + def run(self, ctx, value, flag=False): + pass + + assert varnames(partial(Callback().run, "c")) == (("value",), ("flag",)) + assert varnames(partial(Callback().run, ctx="c")) == ((), ("ctx", "value", "flag")) + + +@pytest.mark.parametrize( + "function, expected", [(len, (("obj",), ())), ([].count, (("value",), ()))] +) +def test_varnames_builtin_signature(function, expected) -> None: + assert varnames(function) == expected + + +@pytest.mark.parametrize( + "function, error", [(42, TypeError), (partial(str, "c"), ValueError)] +) +def test_varnames_signature_error(function, error) -> None: + with pytest.raises(error): + varnames(function) + + +@pytest.mark.skipif(sys.version_info < (3, 14), reason="Requires deferred annotations") +def test_varnames_partial_deferred_annotation() -> None: + def callback( + ctx: str, + value: MissingType, # type: ignore[name-defined] # noqa: F821 + ) -> None: + pass + + assert varnames(partial(callback, "c")) == (("value",), ()) diff --git a/testing/test_pluginmanager.py b/testing/test_pluginmanager.py index f145a27c..1569b2e6 100644 --- a/testing/test_pluginmanager.py +++ b/testing/test_pluginmanager.py @@ -2,6 +2,8 @@ ``PluginManager`` unit and public API testing. """ +from functools import partial +from functools import wraps import importlib.metadata import types from typing import Any @@ -1421,3 +1423,72 @@ def he_method1(self, arg): # The name is free again. pm.register(plugin, "falsy") assert pm.is_registered(plugin) + + +@pytest.mark.parametrize("binding", ["positional", "keyword", "middle_keyword"]) +@pytest.mark.parametrize("decorated", [False, True]) +@pytest.mark.parametrize("explicit", [False, True]) +def test_call_extra_partial_signature( + pm: PluginManager, binding, decorated, explicit +) -> None: + class Hooks: + @hookspec + def calculate(self, value=3, other=4): + pass + + class Plugin: + @hookimpl + def calculate(self, value, other): + return ("registered", value, other) + + def leading(ctx, value, other=20): + return (ctx, value, other) + + def middle(value, ctx, other=20): + return (ctx, value, other) + + function = middle if binding == "middle_keyword" else leading + if decorated: + original = function + + @wraps(original) + def wrapped(*args, **kwargs): + return original(*args, **kwargs) + + function = wrapped + + extra = ( + partial(function, "c") + if binding == "positional" + else partial(function, ctx="c") + ) + pm.add_hookspecs(Hooks) + pm.register(Plugin()) + kwargs = {"value": 7, "other": 8} if explicit else {} + value, other = (7, 8) if explicit else (3, 4) + assert pm.hook.calculate.call_extra([extra], kwargs) == [ + ("c", value, other), + ("registered", value, other), + ] + assert pm.hook.calculate(value=9, other=10) == [("registered", 9, 10)] + + +def test_call_extra_builtin_signature(pm: PluginManager) -> None: + class Hooks: + @hookspec + def calculate(self, obj): + pass + + pm.add_hookspecs(Hooks) + assert pm.hook.calculate.call_extra([len], {"obj": [1, 2, 3]}) == [3] + + +def test_call_extra_uninspectable_signature(pm: PluginManager) -> None: + class Hooks: + @hookspec + def calculate(self, value): + pass + + pm.add_hookspecs(Hooks) + with pytest.raises(ValueError): + pm.hook.calculate.call_extra([partial(str, "c")], {"value": 7})