Ask Your Question

How do you type hint a decorator that modifies the function parameters or signature?

asked 2023-02-19 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-02-14 05:00:00 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools


Asked: 2023-02-19 11:00:00 +0000

Seen: 13 times

Last updated: Feb 14 '22