]> granicus.if.org Git - python/commitdiff
bpo-38013: make async_generator_athrow object tolerant to throwing exceptions (GH...
authorAndrew Svetlov <andrew.svetlov@gmail.com>
Tue, 17 Sep 2019 12:59:49 +0000 (15:59 +0300)
committerMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Tue, 17 Sep 2019 12:59:49 +0000 (05:59 -0700)
Even when the helper is not started yet.

This behavior follows conventional generator one.
There is no reason for `async_generator_athrow` to handle `gen.throw()` differently.

https://bugs.python.org/issue38013

Lib/test/test_asyncgen.py
Misc/NEWS.d/next/Core and Builtins/2019-09-12-19-50-01.bpo-38013.I7btD0.rst [new file with mode: 0644]
Objects/genobject.c

index 71b0968c7944d6cabe0de937911281caec0fd1c2..3a8d5fd4007f0f4aa3d6c39c8b82ca59e1a1dee0 100644 (file)
@@ -1125,6 +1125,28 @@ class AsyncGenAsyncioTest(unittest.TestCase):
         res = self.loop.run_until_complete(run())
         self.assertEqual(res, [i * 2 for i in range(1, 10)])
 
+    def test_asyncgen_nonstarted_hooks_are_cancellable(self):
+        # See https://bugs.python.org/issue38013
+        messages = []
+
+        def exception_handler(loop, context):
+            messages.append(context)
+
+        async def async_iterate():
+            yield 1
+            yield 2
+
+        async def main():
+            loop = asyncio.get_running_loop()
+            loop.set_exception_handler(exception_handler)
+
+            async for i in async_iterate():
+                break
+
+        asyncio.run(main())
+
+        self.assertEqual([], messages)
+
 
 if __name__ == "__main__":
     unittest.main()
diff --git a/Misc/NEWS.d/next/Core and Builtins/2019-09-12-19-50-01.bpo-38013.I7btD0.rst b/Misc/NEWS.d/next/Core and Builtins/2019-09-12-19-50-01.bpo-38013.I7btD0.rst
new file mode 100644 (file)
index 0000000..a61aa48
--- /dev/null
@@ -0,0 +1,3 @@
+Allow to call ``async_generator_athrow().throw(...)`` even for non-started
+async generator helper. It fixes annoying warning at the end of
+:func:`asyncio.run` call.
index 9f490b4e2e483dd22e799b132142acb9cf0619c1..82e6e55868f61784a5197a0b3f7a0db7b3e3b9fd 100644 (file)
@@ -1884,11 +1884,6 @@ async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
 {
     PyObject *retval;
 
-    if (o->agt_state == AWAITABLE_STATE_INIT) {
-        PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
-        return NULL;
-    }
-
     if (o->agt_state == AWAITABLE_STATE_CLOSED) {
         PyErr_SetNone(PyExc_StopIteration);
         return NULL;