]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.12] gh-131670: Fix crash in `anext()` when `__anext__` is sync and raises (GH...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Mon, 24 Mar 2025 19:18:29 +0000 (20:18 +0100)
committerGitHub <noreply@github.com>
Mon, 24 Mar 2025 19:18:29 +0000 (19:18 +0000)
gh-131670: Fix crash in `anext()` when `__anext__` is sync and raises (GH-131682)
(cherry picked from commit 929afd1d6ee4fb89ac818037effe6577947103de)

Co-authored-by: sobolevn <mail@sobolevn.me>
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Lib/test/test_asyncgen.py
Misc/NEWS.d/next/Core_and_Builtins/2025-03-24-19-38-53.gh-issue-131670.IffOZj.rst [new file with mode: 0644]
Python/bltinmodule.c

index b5a786eda4e1a6a8bfa7356e525ca0d135d344e3..07aa088ecf31a5de3faae921879881443d5b007b 100644 (file)
@@ -1117,6 +1117,26 @@ class AsyncGenAsyncioTest(unittest.TestCase):
 
         self.loop.run_until_complete(run())
 
+    def test_sync_anext_raises_exception(self):
+        # See: https://github.com/python/cpython/issues/131670
+        msg = 'custom'
+        for exc_type in [
+            StopAsyncIteration,
+            StopIteration,
+            ValueError,
+            Exception,
+        ]:
+            exc = exc_type(msg)
+            with self.subTest(exc=exc):
+                class A:
+                    def __anext__(self):
+                        raise exc
+
+                with self.assertRaisesRegex(exc_type, msg):
+                    anext(A())
+                with self.assertRaisesRegex(exc_type, msg):
+                    anext(A(), 1)
+
     def test_async_gen_asyncio_anext_stopiteration(self):
         async def foo():
             try:
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-03-24-19-38-53.gh-issue-131670.IffOZj.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-03-24-19-38-53.gh-issue-131670.IffOZj.rst
new file mode 100644 (file)
index 0000000..812a75a
--- /dev/null
@@ -0,0 +1 @@
+Fix :func:`anext` failing on sync :meth:`~object.__anext__` raising an exception.
index ab87ee4fc4dfe9be37b60ceee698129ddc344a06..2ae28693bee05c4a51c698930aa79de2cb9ac2db 100644 (file)
@@ -1685,6 +1685,9 @@ builtin_anext_impl(PyObject *module, PyObject *aiterator,
     }
 
     awaitable = (*t->tp_as_async->am_anext)(aiterator);
+    if (awaitable == NULL) {
+        return NULL;
+    }
     if (default_value == NULL) {
         return awaitable;
     }