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.
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
Asked: 2023-02-19 11:00:00 +0000
Seen: 7 times
Last updated: Feb 14 '22
What is the method of displaying a new line in the hint produced from a comment in VS Code?
How can JSON be decoded while using a universal interface as a field?
How can a new object with a specific type be created in Angular 2 using the domain model?
What is a more effective method to verify the type of an Array containing elements of any type?
How can I remove items from the Symfony dropdown form type?
How can I create a new table by changing the current table type?
How can the project type be modified from a class library to a WPF User control library?