Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we call a normal function where a coroutine is expected?

Consider a coroutine which calls into another coroutine:

async def foo(bar):
     result = await bar()
     return result

This works fine if bar is a coroutine. What do I need to do (i.e. with what do I need to wrap the call to bar) so that this code does the right thing if bar is a normal function?

It is perfectly possible to define a coroutine with async def even if it never does anything asynchronous (i.e. never uses await). However, the question asks how to wrap/modify/call a regular function bar inside the code for foo such that bar can be awaited.

like image 428
DanielSank Avatar asked Jul 24 '16 23:07

DanielSank


People also ask

Is a coroutine a function?

A coroutine is a function that can suspend its execution (yield) until the given YieldInstruction finishes.

What is the difference between async and normal function?

If we want to "await" some functions, why not just use a normal function. If the function you await doesn't need to communicate with the outside world (e.g. if it just shuffles data in a dict or so), it can and should be a normal function. On the other hand, if it needs to do IO, it should be an async function.

Is coroutine a function in Python?

Python Coroutine In Python, coroutines are similar to generators but with few extra methods and slight changes in how we use yield statements. Generators produce data for iteration while coroutines can also consume data. whatever value we send to coroutine is captured and returned by (yield) expression.


1 Answers

Simply wrap your synchronous function with asyncio.coroutine if needed:

if not asyncio.iscoroutinefunction(bar):
    bar = asyncio.coroutine(bar)

Since it is safe to re-wrap a coroutine, the coroutine function test is actually not required:

async_bar = asyncio.coroutine(sync_or_async_bar)

Therefore, your code can be re-written as follows:

async def foo(bar):
     return await asyncio.coroutine(bar)()
like image 132
Vincent Avatar answered Sep 22 '22 06:09

Vincent