Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/817.bugfix.rst
Original file line number Diff line number Diff line change
@@ -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.
43 changes: 40 additions & 3 deletions src/pluggy/_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from collections.abc import Callable
from collections.abc import Mapping
from functools import partial
import inspect
import sys
import types
Expand Down Expand Up @@ -254,13 +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.
"""
original = func
is_bound = False
if inspect.isclass(func):
try:
Expand All @@ -279,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
Expand All @@ -288,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]
Expand Down Expand Up @@ -325,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__ = (
Expand Down
4 changes: 2 additions & 2 deletions src/pluggy/_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
82 changes: 82 additions & 0 deletions testing/test_helpers.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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",), ())
71 changes: 71 additions & 0 deletions testing/test_pluginmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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})
Loading