v0.166.0
 1import annotationlib
 2import functools
 3import inspect
 4from collections.abc import Callable
 5from typing import Any
 6
 7
 8@functools.lru_cache(maxsize=512)
 9def _get_func_parameters(
10    func: Callable[..., Any], remove_first: bool
11) -> tuple[inspect.Parameter, ...]:
12    parameters = tuple(
13        inspect.signature(
14            func, annotation_format=annotationlib.Format.FORWARDREF
15        ).parameters.values()
16    )
17    if remove_first:
18        parameters = parameters[1:]
19    return parameters
20
21
22def _get_callable_parameters(
23    meth_or_func: Callable[..., Any],
24) -> tuple[inspect.Parameter, ...]:
25    is_method = inspect.ismethod(meth_or_func)
26    func = meth_or_func.__func__ if is_method else meth_or_func
27    return _get_func_parameters(func, remove_first=is_method)
28
29
30def func_accepts_kwargs(func: Callable[..., Any]) -> bool:
31    """Return True if function 'func' accepts keyword arguments **kwargs."""
32    return any(p for p in _get_callable_parameters(func) if p.kind == p.VAR_KEYWORD)
33
34
35def method_has_no_args(meth: Callable[..., Any]) -> bool:
36    """Return True if a method only accepts 'self'."""
37    count = len(
38        [p for p in _get_callable_parameters(meth) if p.kind == p.POSITIONAL_OR_KEYWORD]
39    )
40    return count == 0 if inspect.ismethod(meth) else count == 1