[Python] Decorator changes function structure

Discussão em 'Python' iniciado por Stack, Março 12, 2025.

  1. Stack

    Stack Membro Participativo

    I'm facing a problem with annotating decorators. A raw function can take some arguments and a 'deps' argument. The decorator itself substitutes this argument. Question: how to annotate this decorator and will 'wraps' work correctly? Code:

    P = ParamSpec("P")
    T = TypeVar("T")

    class Injector:
    _registered_dependencies: dict[str, Any] = {}
    def __init__(self, *dependency: str):
    self.dependency = dependency


    def __call__(self, func: Callable[Concatenate[dict[str, Any], P], T]) -> Callable[P, T]:
    @functools.wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
    if "deps" in kwargs:
    raise ValueError("Argument 'deps' is already provided and will be overwritten.")
    try:
    deps = {
    i: self.__class__._registered_dependencies for i in self.dependency
    }
    except KeyError as e:
    raise KeyError(f"Dependency {e.args[0]} is not registered")
    return func(*args, **kwargs, deps=deps)
    return wrapper


    Tried using Concatenate[dict[str, Any], P] in __call__ types, also swapping arguments in Concatenate in places, but mypy still swears.

    Continue reading...

Compartilhe esta Página