Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 929afd1

Browse files
sobolevnpicnixz
andauthoredMar 24, 2025
gh-131670: Fix crash in anext() when __anext__ is sync and raises (#131682)
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
1 parent 5fef4ff commit 929afd1

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed
 

‎Lib/test/test_asyncgen.py

+20
Original file line numberDiff line numberDiff line change
@@ -1169,6 +1169,26 @@ async def run():
11691169

11701170
self.loop.run_until_complete(run())
11711171

1172+
def test_sync_anext_raises_exception(self):
1173+
# See: https://github.com/python/cpython/issues/131670
1174+
msg = 'custom'
1175+
for exc_type in [
1176+
StopAsyncIteration,
1177+
StopIteration,
1178+
ValueError,
1179+
Exception,
1180+
]:
1181+
exc = exc_type(msg)
1182+
with self.subTest(exc=exc):
1183+
class A:
1184+
def __anext__(self):
1185+
raise exc
1186+
1187+
with self.assertRaisesRegex(exc_type, msg):
1188+
anext(A())
1189+
with self.assertRaisesRegex(exc_type, msg):
1190+
anext(A(), 1)
1191+
11721192
def test_async_gen_asyncio_anext_stopiteration(self):
11731193
async def foo():
11741194
try:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :func:`anext` failing on sync :meth:`~object.__anext__` raising an exception.

‎Python/bltinmodule.c

+3
Original file line numberDiff line numberDiff line change
@@ -1837,6 +1837,9 @@ builtin_anext_impl(PyObject *module, PyObject *aiterator,
18371837
}
18381838

18391839
awaitable = (*t->tp_as_async->am_anext)(aiterator);
1840+
if (awaitable == NULL) {
1841+
return NULL;
1842+
}
18401843
if (default_value == NULL) {
18411844
return awaitable;
18421845
}

0 commit comments

Comments
 (0)
Failed to load comments.