Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...