Skip to content

Commit a93a663

Browse files
zsol1st1
authored andcommitted
[3.7] bpo-33363: raise SyntaxError for async for/with outside async functions (GH-6616). (GH-6619)
1 parent dd3ede7 commit a93a663

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

Lib/test/test_coroutines.py

Lines changed: 16 additions & 1 deletion
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):
Lines changed: 2 additions & 0 deletions
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.

Python/compile.c

Lines changed: 7 additions & 0 deletions
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);

0 commit comments

Comments
 (0)