Python learning--async/await

With @asyncio.coroutine provided by asyncio, you can mark a generator as a coroutine type, and then use yield from inside the coroutine to call another coroutine to implement asynchronous operations.

In order to simplify and better identify asynchronous IO, new syntax async and await have been introduced starting from Python 3.5, which can make coroutine's code more concise and readable.

Please note that async and awit are new grammars for coroutine. To use the new grammar, you only need to do two simple replacements:

  1. Replace @asyncio.coroutine with async;
  2. Replace yield from with await.

Let's compare the code in the previous section:

@asyncio.coroutine
def hello():
    print("Hello world!")
    r = yield from asyncio.sleep(1)
    print("Hello again!")

Rewritten with the new syntax as follows:

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

summary

Python has provided async and await new syntax for asyncio since version 3.5;

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

Guess you like

Origin blog.csdn.net/qq_44787943/article/details/112645018