[3.7] bpo-33363: raise SyntaxError for async for/with outside async f… · python/cpython@a93a663

File tree

3 files changed

lines changed

  • Misc/NEWS.d/next/Core and Builtins

3 files changed

lines changed

Original file line numberDiff line numberDiff line change

@@ -362,7 +362,22 @@ async def bar(): pass

362362

"""def foo():

363363

async def bar():

364364

pass\nawait a

365-

"""]

365+

""",

366+

"""def foo():

367+

async for i in arange(2):

368+

pass

369+

""",

370+

"""def foo():

371+

async with resource:

372+

pass

373+

""",

374+

"""async with resource:

375+

pass

376+

""",

377+

"""async for i in arange(2):

378+

pass

379+

""",

380+

]

366381
367382

for code in samples:

368383

with self.subTest(code=code), self.assertRaises(SyntaxError):

Original file line numberDiff line numberDiff line change

@@ -0,0 +1,2 @@

1+

Raise a SyntaxError for ``async with`` and ``async for`` statements outside

2+

of async functions.

Original file line numberDiff line numberDiff line change

@@ -2339,6 +2339,10 @@ compiler_async_for(struct compiler *c, stmt_ty s)

23392339

basicblock *try, *except, *end, *after_try, *try_cleanup,

23402340

*after_loop_else;

23412341
2342+

if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {

2343+

return compiler_error(c, "'async for' outside async function");

2344+

}

2345+
23422346

PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);

23432347

if (stop_aiter_error == NULL) {

23442348

return 0;

@@ -4204,6 +4208,9 @@ compiler_async_with(struct compiler *c, stmt_ty s, int pos)

42044208

withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);

42054209
42064210

assert(s->kind == AsyncWith_kind);

4211+

if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {

4212+

return compiler_error(c, "'async with' outside async function");

4213+

}

42074214
42084215

block = compiler_new_block(c);

42094216

finally = compiler_new_block(c);