Async Generators:yield Inside Async def functions
If you use yield in async def, the answer is to generate an asynchronous generator function, which can be confusing if you have a generator, a framework such as twisted, tornado, or a yield from experience.
Therefore, before continuing to study, we should bear in mind these several points:
1. The Cheng generator is a completely different concept;
2. The asynchronous generator is similar to the normal generator;
3. For iterations with IO, async for
replace the normal one for
.
The previous chapter uses asynchronous iterators to demonstrate interaction with Redis, which is actually easier with asynchronous generators.
import asynciofrom aioredis import create_redisasync def main(): redis = await create_redis((‘localhost‘, 6379)) keys = [‘America‘, ‘Africa‘, ‘Europe‘, ‘Asia‘] async for value in one_at_a_time(redis, keys): # 1 await process(value)async def one_at_a_time(redis, keys): # 2 for k in keys: value = await redis.get(k) # 3 yield value # 4asyncio.get_event_loop().run_until_complete(main())
Almost the same, just changed a name;
Now that the function is declared with async def, and yield is used within the function, it can be identified as an asynchronous generator function;
Do not need to be as complex as the previous example, directly let loop to deal with;
Yield values like a common generator.
Just as the common generator makes the code shorter, asynchronous generators also have the same advantages in asynchronous programming, and may be a bit more complicated for beginners, but they can be adapted to practice a bit more.
Deep Asyncio (ix) asynchronous generators