Skip to content

Commit c275312

Browse files
asvetlovmiss-islington
authored andcommitted
bpo-38013: make async_generator_athrow object tolerant to throwing exceptions (GH-16070)
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
1 parent 5f5f11f commit c275312

File tree

3 files changed

+25
-5
lines changed

3 files changed

+25
-5
lines changed

Lib/test/test_asyncgen.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1125,6 +1125,28 @@ async def run():
11251125
res = self.loop.run_until_complete(run())
11261126
self.assertEqual(res, [i * 2 for i in range(1, 10)])
11271127

1128+
def test_asyncgen_nonstarted_hooks_are_cancellable(self):
1129+
# See https://bugs.python.org/issue38013
1130+
messages = []
1131+
1132+
def exception_handler(loop, context):
1133+
messages.append(context)
1134+
1135+
async def async_iterate():
1136+
yield 1
1137+
yield 2
1138+
1139+
async def main():
1140+
loop = asyncio.get_running_loop()
1141+
loop.set_exception_handler(exception_handler)
1142+
1143+
async for i in async_iterate():
1144+
break
1145+
1146+
asyncio.run(main())
1147+
1148+
self.assertEqual([], messages)
1149+
11281150

11291151
if __name__ == "__main__":
11301152
unittest.main()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Allow to call ``async_generator_athrow().throw(...)`` even for non-started
2+
async generator helper. It fixes annoying warning at the end of
3+
:func:`asyncio.run` call.

Objects/genobject.c

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1884,11 +1884,6 @@ async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args)
18841884
{
18851885
PyObject *retval;
18861886

1887-
if (o->agt_state == AWAITABLE_STATE_INIT) {
1888-
PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
1889-
return NULL;
1890-
}
1891-
18921887
if (o->agt_state == AWAITABLE_STATE_CLOSED) {
18931888
PyErr_SetNone(PyExc_StopIteration);
18941889
return NULL;

0 commit comments

Comments
 (0)