1

I have a list of tasks that I am awaiting and the fastest response will be saved and rest will be cancelled

done, pending = await asyncio.wait(
    futures, return_when=FIRST_COMPLETED)

print(done.pop().result())

for future in pending:
    future.cancel()

Each of these futures has this

session = asyncio.CreateSession()
# some code to request
# some code to process response
await session.close()

When I cancel the other futures, I get a warning

Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x10f95c6d8>

What is the best way to close this open session before cancelling the task?

Abhinav_A
  • 58
  • 7

1 Answers1

1

1)

for future in pending:
    future.cancel()

If you want to cancel something you should not only call cancel() method but also await task actually cancelled:

from contextlib import suppress

for task in pending:
    task.cancel()
    with suppress(asyncio.CancelledError):
        await task

Please read this answer to see how cancellation works.

2)

session = asyncio.CreateSession()
# some code to request
# some code to process response
await session.close()

And somewhere between this lines CancelledError (or other exception) can be raised. If it'll happen line await session.close() would never be reached.

Everywhere in Python if you take some resources and would need to free it later you should always wrap all your code between taking/freeing to try/finally block:

session = asyncio.CreateSession()
try:
    # some code to request
    # some code to process response
finally:
    await session.close()

Again, it's common pattern related not only to asyncio.

Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159
  • I came across the 'with' syntax. Your explanation is basically what 'with' does. Am I correct? – Abhinav_A Nov 22 '17 at 07:24
  • @Abhinav_A yes, that's what `with` syntax does in current case (and usually in many other cases). Even better here would be to use newer `async with` syntax (see first code snippet [here](https://stackoverflow.com/a/47172471/1113207) for example). – Mikhail Gerasimov Nov 22 '17 at 09:04