I'm creating a decorator, and I'd like the typehint to be preserved. However, I need to alter the return type a little bit. The Mypy docs contain information on how to do this if your decorated function signature is the same as the original one, but I'm not sure how to do this if the return type is altered.
As an example, here is my original function:
async def simple_func(a: int) -> int:
'Simple sleeper function to test calling mechanics'
return a + 1
It has the signature (int) -> Awaitable[int].
Here is how I use it:
t_wrap = make_sync(simple_func)
_ = get_event_loop()
assert t_wrap(4) == 5
When I look at the type of t_wrap using pyright or a similar tool in my editor, it is (*args, **kwargs) -> int, rather than (int) -> int.
My decorator function is as follows:
from functools import wraps
from typing import Callable, TypeVar
R = TypeVar('R')
def make_sync(fn: Callable[..., Awaitable[R]]) -> Callable[..., R]:
@wraps(fn)
def sync_version_of_function(*args, **kwargs):
stuff stuff stuff
r = fn(*args, **kwargs)
stuff stuff stuff
return sync_version_of_function
What I'm missing is how to deal with the ... - I'd like to define a TypeVar A to represent the list of arguments, but I can't figure out how to approach that.