]> granicus.if.org Git - python/commitdiff
[3.7] bpo-33363: raise SyntaxError for async for/with outside async functions (GH...
authorZsolt Dollenstein <zsol.zsol@gmail.com>
Fri, 27 Apr 2018 22:33:37 +0000 (15:33 -0700)
committerYury Selivanov <yury@magic.io>
Fri, 27 Apr 2018 22:33:37 +0000 (18:33 -0400)
Lib/test/test_coroutines.py
Misc/NEWS.d/next/Core and Builtins/2018-04-26-22-48-28.bpo-33363.8RCnN2.rst [new file with mode: 0644]
Python/compile.c

index ea54bca0df0dfe36eadc8e565c11647e349490a8..ac24f39767385ff3bf9e16ec650a90d3b4f1873d 100644 (file)
@@ -362,7 +362,22 @@ class AsyncBadSyntaxTest(unittest.TestCase):
             """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):
diff --git a/Misc/NEWS.d/next/Core and Builtins/2018-04-26-22-48-28.bpo-33363.8RCnN2.rst b/Misc/NEWS.d/next/Core and Builtins/2018-04-26-22-48-28.bpo-33363.8RCnN2.rst
new file mode 100644 (file)
index 0000000..ad8d248
--- /dev/null
@@ -0,0 +1,2 @@
+Raise a SyntaxError for ``async with`` and ``async for`` statements outside
+of async functions.
index d4245e2f4e5092d1d1d4924bc2a32aaabf7a3c9e..62d78867e0776a4f7c761c616b7ba426030b5bd0 100644 (file)
@@ -2339,6 +2339,10 @@ compiler_async_for(struct compiler *c, stmt_ty s)
     basicblock *try, *except, *end, *after_try, *try_cleanup,
                *after_loop_else;
 
+    if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
+        return compiler_error(c, "'async for' outside async function");
+    }
+
     PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration);
     if (stop_aiter_error == NULL) {
         return 0;
@@ -4204,6 +4208,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);