65 async/await

Source: Internet
Author: User

With asyncio the provided @asyncio.coroutine , you can mark a generator as the coroutine type, and then implement the asynchronous operation within Coroutine by yield from calling another coroutine.

To simplify and better identify asynchronous IO, the new syntax is introduced starting with Python 3.5 async await , which makes Coroutine's code easier to read.

Note that, async and the await new syntax for coroutine, to use the new syntax, you only need to do a two-step simple substitution:

    1. To @asyncio.coroutine Replace with async ;
    2. yield fromReplace with a await .

Let's compare the code in the previous section:

@asyncio. Coroutinedef Hello ():    print ("Hello world! " )    yield from Asyncio.sleep (1)    print ("  Hello again! ")

Rewrite the following in the new syntax:

Async def hello ():    print ("Hello world! " )    await asyncio.sleep (1)    print ("Hello again! ")

The rest of the code remains the same.

Summary

Python begins with the 3.5 version asyncio async await of the new syntax provided;

Note that the new syntax can only be used in Python 3.5 and later, and if you use version 3.4, you still need to use the previous section of the scenario.

65 async/await

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.