Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To type hint a decorator that modifies the function parameters or signature, you can use the Callable type hint from the typing module. The Callable type hint specifies the type of a callable object, such as a function or a method. It takes two or more arguments, with the first argument being the type of the arguments to the callable and the last argument being the return type of the callable.

For example, let's say we have a decorator called my_decorator that adds a new parameter to the function and modifies the function's return type. We can type hint this decorator like this:

from typing import Callable

def my_decorator(func: Callable[..., str]) -> Callable[..., int]:
    def wrapper(*args: Any, **kwargs: Any) -> int:
        # Add a new parameter to the function
        new_arg = 123
        args = args + (new_arg,)

        # Call the function and modify the return value
        result = func(*args, **kwargs)
        return int(result)

    return wrapper

In this example, we use Callable[..., str] to indicate that the func parameter is a callable that takes any arguments and returns a str. We then use Callable[..., int] to indicate that the return type of my_decorator is a callable that takes the same arguments as func, plus an additional integer parameter, and returns an integer.