Skip to content

bpo-33786: Fix asynchronous generators to handle GeneratorExit in athrow() #7467

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 3 commits into from
Jun 8, 2018
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
2 changes: 1 addition & 1 deletion Lib/contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ async def __aexit__(self, typ, value, traceback):
# in this implementation
try:
await self.gen.athrow(typ, value, traceback)
raise RuntimeError("generator didn't stop after throw()")
raise RuntimeError("generator didn't stop after athrow()")
except StopAsyncIteration as exc:
return exc is not value
except RuntimeError as exc:
Expand Down
56 changes: 56 additions & 0 deletions Lib/test/test_asyncgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,31 @@ def sync_iterate(g):
res.append(str(type(ex)))
return res

def async_iterate(g):
res = []
while True:
an = g.__anext__()
try:
while True:
try:
an.__next__()
except StopIteration as ex:
if ex.args:
res.append(ex.args[0])
break
else:
res.append('EMPTY StopIteration')
break
except StopAsyncIteration:
raise
except Exception as ex:
res.append(str(type(ex)))
break
except StopAsyncIteration:
res.append('STOP')
break
return res

def async_iterate(g):
res = []
while True:
Expand Down Expand Up @@ -297,6 +322,37 @@ async def gen():
"non-None value .* async generator"):
gen().__anext__().send(100)

def test_async_gen_exception_11(self):
def sync_gen():
yield 10
yield 20

def sync_gen_wrapper():
yield 1
sg = sync_gen()
sg.send(None)
try:
sg.throw(GeneratorExit())
except GeneratorExit:
yield 2
yield 3

async def async_gen():
yield 10
yield 20

async def async_gen_wrapper():
yield 1
asg = async_gen()
await asg.asend(None)
try:
await asg.athrow(GeneratorExit())
except GeneratorExit:
yield 2
yield 3

self.compare_generators(sync_gen_wrapper(), async_gen_wrapper())

def test_async_gen_api_01(self):
async def gen():
yield 123
Expand Down
22 changes: 22 additions & 0 deletions Lib/test/test_contextlib_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,28 @@ async def __aexit__(self, *args):
async with manager as context:
self.assertIs(manager, context)

@_async_test
async def test_async_gen_propagates_generator_exit(self):
# A regression test for https://bugs.python.org/issue33786.

@asynccontextmanager
async def ctx():
yield

async def gen():
async with ctx():
yield 11

ret = []
exc = ValueError(22)
with self.assertRaises(ValueError):
async with ctx():
async for val in gen():
ret.append(val)
raise exc

self.assertEqual(ret, [11])

def test_exit_is_abstract(self):
class MissingAexit(AbstractAsyncContextManager):
pass
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix asynchronous generators to handle GeneratorExit in athrow() correctly
15 changes: 7 additions & 8 deletions Objects/genobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1876,21 +1876,20 @@ async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg)
return NULL;

check_error:
if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)) {
if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
PyErr_ExceptionMatches(PyExc_GeneratorExit))
{
o->agt_state = AWAITABLE_STATE_CLOSED;
if (o->agt_args == NULL) {
/* when aclose() is called we don't want to propagate
StopAsyncIteration; just raise StopIteration, signalling
that 'aclose()' is done. */
StopAsyncIteration or GeneratorExit; just raise
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I understand, this will make .aclose() raise StopIteration in the usual case (when generator doesn't handle the GeneratorExit). What about .athrow(), how will it behave? Shouldn't their behavior be similar to that of .close() and .throw() for sync generators, where .close() swallows the GeneratorExit and .throw() doesn't?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I understand, this will make .aclose() raise StopIteration in the usual case (when generator doesn't handle the GeneratorExit).

Keep in mind, that raising StopIteration from any of a***() methods just means that they are returning. They are all iterators.

What about .athrow(), how will it behave?

The idea here:

  1. athrow() and aclose() share one implementation.

  2. aclose() is basically an athrow(GeneratorExit).

  3. When aclose() is called and the generator propagates GeneratorExit, it means that everything is fine and the aclose() call was successful. We raise StopIteration to make aclose() awaitable return.

  4. When athrow() is called we don't want to trap any exceptions at all. So we raise StopIteration only if the asynchronous generator swallowed the thrown error and yielded (asynchronously).

This is a bit complex, I know. I explained how asynchronous generators work in detail here: https://www.python.org/dev/peps/pep-0525/#implementation-details

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, now I get it

StopIteration, signalling that this 'aclose()' await
is done.
*/
PyErr_Clear();
PyErr_SetNone(PyExc_StopIteration);
}
}
else if (PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
o->agt_state = AWAITABLE_STATE_CLOSED;
PyErr_Clear(); /* ignore these errors */
PyErr_SetNone(PyExc_StopIteration);
}
return NULL;
}

Expand Down