Skip to content

Commit e239650

Browse files
zsol1st1
authored andcommitted
bpo-33363: raise SyntaxError for async for/with outside async functions (#6616)
1 parent 078c4e3 commit e239650

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
@@ -2447,6 +2447,10 @@ static int
24472447
compiler_async_for(struct compiler *c, stmt_ty s)
24482448
{
24492449
basicblock *start, *except, *end;
2450+
if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
2451+
return compiler_error(c, "'async for' outside async function");
2452+
}
2453+
24502454
start = compiler_new_block(c);
24512455
except = compiler_new_block(c);
24522456
end = compiler_new_block(c);
@@ -4262,6 +4266,9 @@ compiler_async_with(struct compiler *c, stmt_ty s, int pos)
42624266
withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
42634267

42644268
assert(s->kind == AsyncWith_kind);
4269+
if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
4270+
return compiler_error(c, "'async with' outside async function");
4271+
}
42654272

42664273
block = compiler_new_block(c);
42674274
finally = compiler_new_block(c);

0 commit comments

Comments
 (0)