Skip to content

gh-128078: Clear exception in anext before calling _PyGen_SetStopIterationValue #128780

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Lib/test/test_asyncgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -1152,6 +1152,23 @@ async def run():

self.loop.run_until_complete(run())

def test_async_gen_asyncio_anext_tuple_no_exceptions(self):
# StopAsyncIteration exceptions should be cleared.
# See: https://github.com/python/cpython/issues/128078.

async def foo():
if False:
yield (1, 2)

async def run():
it = foo().__aiter__()
with self.assertRaises(StopAsyncIteration):
await it.__anext__()
res = await anext(it, ('a', 'b'))
self.assertEqual(res, ('a', 'b'))

self.loop.run_until_complete(run())

def test_async_gen_asyncio_anext_stopiteration(self):
async def foo():
try:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a :exc:`SystemError` when using :func:`anext` with a default tuple
value. Patch by Bénédikt Tran.
1 change: 1 addition & 0 deletions Objects/genobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,7 @@ gen_iternext(PyObject *self)
int
_PyGen_SetStopIterationValue(PyObject *value)
{
assert(!PyErr_Occurred());
PyObject *e;

if (value == NULL ||
Expand Down
2 changes: 2 additions & 0 deletions Objects/iterobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,7 @@ anextawaitable_iternext(anextawaitableobject *obj)
return result;
}
if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)) {
PyErr_Clear();
_PyGen_SetStopIterationValue(obj->default_value);
}
return NULL;
Expand All @@ -407,6 +408,7 @@ anextawaitable_proxy(anextawaitableobject *obj, char *meth, PyObject *arg) {
* exception we replace it with a `StopIteration(default)`, as if
* it was the return value of `__anext__()` coroutine.
*/
PyErr_Clear();
_PyGen_SetStopIterationValue(obj->default_value);
}
return NULL;
Expand Down
Loading