Deep Asyncio (ix) asynchronous generators

Source: Internet
Author: User

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())
    1. Almost the same, just changed a name;

    2. 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;

    3. Do not need to be as complex as the previous example, directly let loop to deal with;

    4. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.