Подтвердить что ты не робот

'async for' в Python 3.4

Есть ли способ преобразовать async for выражение Python 3.5 async for оператора в коде Python 3.4?

PEP 0492 говорит, что async for

async for TARGET in ITER:
    BLOCK
else:
    BLOCK2

эквивалентно

iter = (ITER)
iter = type(iter).__aiter__(iter)
running = True
while running:
    try:
        TARGET = await type(iter).__anext__(iter)
    except StopAsyncIteration:
        running = False
    else:
        BLOCK
else:
    BLOCK2

но __aiter__ не существует в Python 3.4

4b9b3361

Ответ 1

Нет, нет, async/await (также __aiter__ и т.д.) Была введена в python 3.5. На py3.4 самым близким является asyncio.gather (если вы можете запускать все задачи одновременно/параллельно и ждать, пока они все не будут завершены) или помещать результаты в asyncio.Queue (который является последовательным, точно так же, как async for). Изменение: см. Последний пример для async for альтернативы, как описано в вопросе.

Вот пример документации ala python для asyncio.gather:

import asyncio

@asyncio.coroutine
def task(id):
    print("task: {}".format(id))
    yield from asyncio.sleep(random.uniform(1, 3))
    return id

tasks = [
    task("A"),
    task("B"),
    task("C")
]
loop = asyncio.get_event_loop()
results = loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
print(results)

Выход:

task: B
task: A
task: C
['A', 'B', 'C']

Вот один для asyncio.Queue:

import asyncio

@asyncio.coroutine
def produce(queue, n):
    for x in range(n):
        print('producing {}/{}'.format(x, n))
        # todo: do something more useful than sleeping :)
        yield from asyncio.sleep(random.random())
        yield from queue.put(str(x))


@asyncio.coroutine
def consume(queue):
    while True:
        item = yield from queue.get()
        print('consuming {}...'.format(item))
        # todo: do something more useful than sleeping :)
        yield from asyncio.sleep(random.random())
        queue.task_done()


@asyncio.coroutine
def run(n):
    queue = asyncio.Queue()
    # schedule the consumer
    consumer = asyncio.ensure_future(consume(queue))
    # run the producer and wait for completion
    yield from produce(queue, n)
    # wait until the consumer has processed all items
    yield from queue.join()
    # the consumer is still awaiting for an item, cancel it
    consumer.cancel()


loop = asyncio.get_event_loop()
loop.run_until_complete(run(10))
loop.close()

Отредактируйте: async for альтернативы, как описано в вопросе:

import asyncio
import random

class StopAsyncIteration(Exception):
    """"""

class MyCounter:
    def __init__(self, count):
        self.count = count

    def __aiter__(self):
        return self

    @asyncio.coroutine
    def __anext__(self):
        if not self.count:
            raise StopAsyncIteration

        return (yield from self.do_something())

    @asyncio.coroutine
    def do_something(self):
        yield from asyncio.sleep(random.uniform(0, 1))
        self.count -= 1
        return self.count

@asyncio.coroutine
def getNumbers():
    i = MyCounter(10).__aiter__()
    while True:
        try:
            row = yield from i.__anext__()
        except StopAsyncIteration:
            break
        else:
            print(row)

loop = asyncio.get_event_loop()
loop.run_until_complete(getNumbers())
loop.close()

Обратите внимание, что это можно упростить, удалив и __aiter__ и __aiter__ и __anext__ исключение stop в самом методе do_something или __anext__ когда это будет сделано, сторожевой результат (обычно недопустимое значение, например: None, "", -1 и т.д.)