Python 3.5: “async with” results in SyntaxError. Why? [duplicate]

别等时光非礼了梦想. 提交于 2020-01-20 03:53:08

问题


I am using Python 3.5, which, according to PEP 492 should have access to the async with syntax, yet I get a SyntaxError when I try to use it. What am I doing wrong?

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:


You can not use async with without async function. As the docs say:

It is a SyntaxError to use async with outside of an async def function.

But this code will work:

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

Or have a look at the example from the docs.



来源:https://stackoverflow.com/questions/42285685/python-3-5-async-with-results-in-syntaxerror-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!