Important rule: Different coroutines own different contexts.
- The
example1.py
runs one coroutine with async_generator, theasync_generator.__anext__
method runs in same context and thus it works find. - The
example2.py
produces two coroutines with the same async_generator, theasync_generator.__anext__
method runs in different contexts and thus it raises an ValueError exception.
- don't use
reset
in async_generator. - need to ensure the context from
gen.__anext__()
being applied on the procedure of per loop.
async def process_per_loop():
await gen.__anext__()
await proceduer() # do something with same gen.__anext__() context
asyncio.ensure_future(coro()) # do something with copied gen.__anext__() context
- best way is using
async-for
statement.
async for val in gen:
await proceduer() # do something with same gen.__anext__() context
asyncio.ensure_future(coro()) # do something with copied gen.__anext__() context