Skip to content

Commit 3492098

Browse files
miss-islingtonsobolevnpicnixz
authored
[3.13] gh-131670: Fix crash in anext() when __anext__ is sync and raises (GH-131682) (#131686)
gh-131670: Fix crash in `anext()` when `__anext__` is sync and raises (GH-131682) (cherry picked from commit 929afd1) Co-authored-by: sobolevn <[email protected]> Co-authored-by: Bénédikt Tran <[email protected]>
1 parent 9f36dff commit 3492098

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

Lib/test/test_asyncgen.py

Lines changed: 20 additions & 0 deletions
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:
Lines changed: 1 addition & 0 deletions
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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1737,6 +1737,9 @@ builtin_anext_impl(PyObject *module, PyObject *aiterator,
17371737
}
17381738

17391739
awaitable = (*t->tp_as_async->am_anext)(aiterator);
1740+
if (awaitable == NULL) {
1741+
return NULL;
1742+
}
17401743
if (default_value == NULL) {
17411744
return awaitable;
17421745
}

0 commit comments

Comments
 (0)