考虑来自Python文档的this example:
def gen(): # defines a generator function
yield 123
async def agen(): # defines an asynchronous generator function
yield 123
我知道这个示例很简单,但是我{strong>可以使用gen
做什么,而不能使用agen
做什么,反之亦然?我会以什么方式注意到它们的区别?
我认为这个问题会有所帮助,但我仍然不明白: What are the differences between the purposes of generator functions and asynchronous generator functions
答案 0 :(得分:1)
一个适合异步/等待框架,另一个不适合。
首先,常规生成器函数。这里没有合作的多任务处理:
def f():
return 4
def g():
return 5
def gen():
"""cannot call async functions here"""
yield f()
yield g()
def run():
for v in gen():
print(v)
vs下面的 with 协作多任务处理。允许其他任务在await
之后/ async for
async def f():
return 4
async def g():
return 5
async def gen():
"""can await async functions here"""
yield await f()
yield await g()
async def run():
async for v in gen():
print(v)
asyncio.run(run())