Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python type hinting for async function as function argument

I am trying to make sure a function parameter is an async function. So I am playing around with the following code:

async def test(*args, **kwargs):
    pass

def consumer(function_: Optional[Coroutine[Any, Any, Any]]=None):
    func = function_

consumer(test)

But it doesn't work.

I am presented with the following error during type checking in pyCharm:

Expected type 'Optional[Coroutine]', got '(args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Coroutine[Any, Any, None]' instead

Can anyone give me some hints how to solve this ?

like image 827
sanders Avatar asked Mar 19 '18 10:03

sanders


1 Answers

You are looking for:

FuncType = Callable[[Any, Any], Coroutine[Any]]
def consumer(function_: FuncType = None):

Why is the type structured like that? If you declare a function async, what you actually do is wrap it in a new function with the given parameters, which returns a Coroutine.


Since this might be relevant to some people who come here, this is an example of an awaitable function type:

OnAction = Callable[[Foo, Bar], Awaitable[FooBar]]

It is a function that takes Foo, Bar and returns a FooBar

like image 52
Neuron Avatar answered Oct 14 '22 05:10

Neuron