什么是“异步生成器”&它与python3.6中的“协同程序”有何不同

2024-09-29 00:23:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我怀疑这与b/wyield from&;await之间的差异有关

然而,除了将新对象指定为async_generator,我不清楚它与acoroutine之间差异的后果。

(我不知道除了我在标题里写的那个问题之外,我不知道还能怎么问这个问题……)

import asyncio

async def async_generator_spits_out_letters():
    yield 'a'
    yield 'b'
    yield 'c'
    yield 'd'
    await asyncio.sleep(0)

async def coroutine_prints_messages():
    while True:
        print('hi')
        await asyncio.sleep(2)

def test_it():
    print(type(async_generator_spits_out_letters))
    print(type(coroutine_prints_messages))
    # This is how I choose to do newlines....it's easier for me to read. :[
    print(); print()

    print(type(async_generator_spits_out_letters()))
    print(type(coroutine_prints_messages()))

这样可以得到:

^{pr2}$

我搞不清这件事的来龙去脉。。。在


Tags: asyncioasyncdeftype差异awaitoutgenerator
1条回答
网友
1楼 · 发布于 2024-09-29 00:23:06

为了让一个async_generator生成函数在eventloop中运行,它的输出必须包装在coroutine.

这是为了防止async_generator直接将值生成到事件循环中。


import asyncio

# This produces an async_generator
async def xrange(numbers):
    for i in range(numbers):
        yield i
        await asyncio.sleep(0)

# This prevents an async_generator from yielding into the loop.
async def coroutine_wrapper(async_gen, args):
    try:
        print(tuple([i async for i in async_gen(args)]))
    except ValueError:
        print(tuple([(i, j) async for i, j in async_gen(args)]))

循环只与任务和未来类似

如果循环从某个任务接收到一个整数或字符串或..任何不是从future派生的内容,它将中断。在

因此coroutines必须:

  • 产生futures(或{}的子类)
  • 或者不将任何值传递回循环。在

这里是main():

^{pr2}$

输出如下:

BEGIN LOOP:

(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)

END LOOP


type(xrange) == <class 'function'>
type(xrange(20)) == <class 'async_generator'>

type(coroutine_wrapper) == <class 'function'>
type(coroutine_wrapper(xrange,20)) == <class 'coroutine'>

相关问题 更多 >