Python 3.5 - 名称 'await' 未定义

Python 3.5 - Name 'await' is not defined

我正在尝试在 Python 3.5 中尝试新的 await 协程语法。

我有一个像这样的简单例子:

#! /usr/bin/env python
import asyncio

@asyncio.coroutine
def adder(*args, delay):
    while True:
        yield from asyncio.sleep(delay)
        print(sum(args))


def main():
    asyncio.Task(adder(1, 2, 3, delay=5))
    asyncio.Task(adder(10, 20, delay=3))

    loop = asyncio.get_event_loop()
    loop.run_forever()

if __name__ == "__main__":
    main()

我更改了 yield from 行以使用 await 关键字:

await asyncio.sleep(delay)

然后我得到 SyntaxError:

  File "./test.py", line 8
    await asyncio.sleep(delay)
                ^
SyntaxError: invalid syntax

所以我尝试 await (asyncio.sleep(delay)) 看看会发生什么:

Task exception was never retrieved
future: <Task finished coro=<adder() done, defined at c:\python35\Lib\asyncio\coroutines.py:198> exception=NameError("name 'await' is not defined",)>
Traceback (most recent call last):
  File "c:\python35\Lib\asyncio\tasks.py", line 239, in _step
    result = coro.send(value)
  File "c:\python35\Lib\asyncio\coroutines.py", line 200, in coro
    res = func(*args, **kw)
  File "./test.py", line 8, in adder
    await (asyncio.sleep(delay))
NameError: name 'await' is not defined
Task exception was never retrieved
future: <Task finished coro=<adder() done, defined at c:\python35\Lib\asyncio\coroutines.py:198> exception=NameError("name 'await' is not defined",)>
Traceback (most recent call last):
  File "c:\python35\Lib\asyncio\tasks.py", line 239, in _step
    result = coro.send(value)
  File "c:\python35\Lib\asyncio\coroutines.py", line 200, in coro
    res = func(*args, **kw)
  File "./test.py", line 8, in adder
    await (asyncio.sleep(delay))
NameError: name 'await' is not defined

我是不是关键字用错了?为什么 await 没有定义?我的 await 语法来自 this post.

只是为了涵盖我的所有基地:

$ /usr/bin/env python --version

Python 3.5.0

编辑:

我想将括号添加到 await 行是在尝试调用一个函数 await() - 所以这就是为什么它不起作用并给我一个 NameError 的原因。但为什么在这两个示例中都没有识别出关键字?

您必须将函数声明为 async 才能使用 await。替换 yield from 是不够的。

#! /usr/bin/env python
import asyncio

@asyncio.coroutine
async def adder(*args, delay):
    while True:
        await asyncio.sleep(delay)
        print(sum(args))


def main():
    asyncio.Task(adder(1, 2, 3, delay=5))
    asyncio.Task(adder(10, 20, delay=3))
    loop = asyncio.get_event_loop()
    loop.run_forever()

if __name__ == "__main__":
    main()

您需要将您的函数声明为 async 才能使其正常工作。 await 关键字只有在您在文件中包含一个用 async def 声明的函数时才会启用 – 有关详细信息,请参阅 PEP 492

根据 PEP 492await 关键字只能在使用新 async def 语法定义的函数中识别,这消除了对 __future__ 导入的需要。