Python 3.5:“async with”导致SyntaxError。为什么呢?

时间:2017-02-16 22:14:33

标签: python python-3.x coroutine

我正在使用Python 3.5,根据PEP 492,它应该可以访问async with语法,但是当我尝试使用它时,我得到了一个SyntaxError。我做错了什么?

In [14]: sys.version
Out[14]: '3.5.2 (default, Oct 11 2016, 04:59:56) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)]'

In [15]: async with aiohttp.ClientSession() as session:
  File "<ipython-input-15-9799c5ce74cf>", line 1
    async with aiohttp.ClientSession() as session:
             ^
SyntaxError: invalid syntax

1 个答案:

答案 0 :(得分:25)

如果没有async with功能,则无法使用async。正如docs say

  

在异步def函数之外使用async是一个SyntaxError。

但是这段代码可行:

async def some_function():
    async with aiohttp.ClientSession() as session:
        pass

或者查看docs中的示例。