Source: https://stackoverflow.com/q/51245011/6275324
Asyncio somehow breaks coroutine finalization. I believe there may be a bug in C implementation (_asyncio) of tasks or futures. Reproducible within version 3.7.0@python:3.7 docker container.
Consider this example (except and finally blocks will never execute):
import asyncio
async def work():
try:
print('started working')
await asyncio.sleep(3600)
except BaseException as e:
print('caught ' + str(type(e)))
finally:
print('finalization completed')
async def stopper():
await asyncio.sleep(5)
loop.stop()
loop = asyncio.get_event_loop()
loop.create_task(work())
loop.create_task(stopper())
loop.run_forever()
And there is asyncio-free piece of code, which works properly, catching GeneratorExit, thrown by coro destructor:
import asyncio
async def work():
try:
print('started working')
await asyncio.sleep(3600)
except BaseException as e:
print('caught ' + str(type(e)))
finally:
print('finalization completed')
coro = work()
coro.send(None)
del coro |