新 python async 和 await 关键字

New python async and await keywords

有人可以解释一下 PEP 0492: Coroutines with async and await syntax 中概述的新语法吗?

之类的东西之间的主要区别是什么
def do_nothing():
    return

async def do_nothing():
    return

简而言之,因为这是一个广泛的话题:

@asyncio.coroutine
def foo():
    bar = yield from some_async_func()
    print(bar)

asyncio.get_event_loop().run_until_complete(foo())

这定义了一个使用 asyncio 模块的协程。 foo 是协程,它调用协程 some_async_func (因为它调用异步函数,它本身也必须是异步的)。整个装置需要 运行 在事件循环中异步进行。

调用 foo() 生成一个生成器对象,事件循环 运行 直到它不再生成任何东西。 yield from 挂起函数并让给另一个协程,它基本上以相同的方式执行(生成器、直到完成等)。当该生成器完成后,返回值并分配给 bar 并且函数被解冻。

简而言之就是异步编程。

PEP 0492 想通过一些特定的方式改进对这种编程的支持:

  • It is proposed to make coroutines a proper standalone concept in Python [..]
  • It is easy to confuse coroutines with regular generators, since they share the same syntax [..]
  • Whether or not a function is a coroutine is determined by a presence of yield or yield from statements in its body , which can lead to unobvious errors [..]
  • Support for asynchronous calls is limited to expressions where yield is allowed syntactically, limiting the usefulness of syntactic features [..]

这些要点表明协程是一个相当独特的东西,但与语言中的其他东西区别不大,因为它们主要劫持了已经存在的生成器语法。 PEP 希望通过使协程和异步编程成为更易于使用的独立事物来改进这一点。

  • This proposal introduces new syntax and semantics to enhance coroutine support in Python.
  • The following new syntax is used to declare a native coroutine [..]

仅仅将协程提升为原生类型应该是一个明显的改进。它允许您像任何其他类型一样对协程进行类型检测。它还统一了实现。目前有一个 "native" asyncio 协程模块,但也有像 Twisted 这样的第三方库,它们有自己的协程语法和装饰器。

  • This PEP assumes that the asynchronous tasks are scheduled and coordinated by an Event Loop [..] While the PEP is not tied to any specific Event Loop implementation [..]

这是说您将能够使用一种定义的语法编写协程,然后使用您想要的任何兼容的事件循环实现来执行它们。

您可以在 PEP 中阅读其余提案。