[New-bugs-announce] [issue40152] Coroutine hangs if it performs async operations when handling exception sent using throw()

Guilherme Salgado report at bugs.python.org
Thu Apr 2 03:07:01 EDT 2020


New submission from Guilherme Salgado <gsalgado at gmail.com>:

A coroutine will hang forever if it that catches an exception sent via its throw() method and then makes async calls while handling that exception. The same coroutine will complete just fine if the exception is instead raised from within it. Here's a script that demonstrates that:

```
import asyncio
import sys

async def sleep_on_exc(inject):
    if inject:
        asyncio.ensure_future(inject_exc(coro))
    try:
        await asyncio.sleep(0.2)
        if not inject:
            print("Raising KeyboardInterrupt")
            raise KeyboardInterrupt()
    except KeyboardInterrupt:
        print("I'm not done yet")
        await asyncio.sleep(0.1)
        print("Now I'm done")

async def inject_exc(coro):
    await asyncio.sleep(0.1)
    print("Injecting KeyboardInterrupt")
    coro.throw(KeyboardInterrupt)

coro = sleep_on_exc(sys.argv[1] == "inject")
loop = asyncio.get_event_loop()
loop.run_until_complete(coro)
```

```
$ python throw.py raise
Raising KeyboardInterrupt
I'm not done yet
Now I'm done
```

```
$ python throw.py inject
Injecting KeyboardInterrupt
I'm not done yet                     # It hangs forever here until you Ctrl-C
^CTraceback (most recent call last):
...
```

----------
components: asyncio
messages: 365572
nosy: asvetlov, salgado, yselivanov
priority: normal
severity: normal
status: open
title: Coroutine hangs if it performs async operations when handling exception sent using throw()
type: behavior
versions: Python 3.7

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue40152>
_______________________________________


More information about the New-bugs-announce mailing list