By vaer-k


2017-02-16 22:14:33 8 Comments

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 comments

@sobolevn 2017-02-16 22:20:18

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.

@MSeifert 2017-02-16 22:23:34

I think you quoted the wrong section. The correct citation would be the last sentence in the PEP - 492: "New Syntax" section: "It is a SyntaxError to use async with outside of an async def function."

@sobolevn 2017-02-16 22:27:00

@MSeifert thanks, updated!

Related Questions

Sponsored Content

22 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

9 Answered Questions

34 Answered Questions

[SOLVED] How to get the current time in Python

  • 2009-01-06 04:54:23
  • user46646
  • 2943490 View
  • 2534 Score
  • 34 Answer
  • Tags:   python datetime time

60 Answered Questions

[SOLVED] Calling an external command in Python

12 Answered Questions

[SOLVED] How can I make a time delay in Python?

7 Answered Questions

[SOLVED] Understanding Python super() with __init__() methods

28 Answered Questions

[SOLVED] Finding the index of an item given a list containing it in Python

  • 2008-10-07 01:39:38
  • Eugene M
  • 3398271 View
  • 2801 Score
  • 28 Answer
  • Tags:   python list indexing

16 Answered Questions

[SOLVED] What are metaclasses in Python?

10 Answered Questions

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

Sponsored Content