Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion Lib/test/test_coroutines.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,22 @@ async def bar(): pass
"""def foo():
async def bar():
pass\nawait a
"""]
""",
"""def foo():
async for i in arange(2):
pass
""",
"""def foo():
async with resource:
pass
""",
"""async with resource:
pass
""",
"""async for i in arange(2):
pass
""",
]

for code in samples:
with self.subTest(code=code), self.assertRaises(SyntaxError):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Raise a SyntaxError for ``async with`` and ``async for`` statements outside
of async functions.
7 changes: 7 additions & 0 deletions Python/compile.c
Original file line number Diff line number Diff line change
Expand Up @@ -2443,6 +2443,10 @@ static int
compiler_async_for(struct compiler *c, stmt_ty s)
{
basicblock *start, *except, *end;
if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
return compiler_error(c, "'async for' outside async function");
}

start = compiler_new_block(c);
except = compiler_new_block(c);
end = compiler_new_block(c);
Expand Down Expand Up @@ -4258,6 +4262,9 @@ compiler_async_with(struct compiler *c, stmt_ty s, int pos)
withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);

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

block = compiler_new_block(c);
finally = compiler_new_block(c);
Expand Down