mosquito / aio-pika

AMQP 0.9 client designed for asyncio and humans.
https://aio-pika.readthedocs.org/
Apache License 2.0
1.18k stars 186 forks source link

How to close connections gracefully on __del__? #443

Open SerGeRybakov opened 2 years ago

SerGeRybakov commented 2 years ago

I would like to use the aio-pika pre-defined methods await connection.close() and await channel.close() on program finish. With pika I just put them into __del__ method and everyone's happy. But as long as __del__ can't be asynchronous, I'm not able to call them anywhere except __aexit__ (but it's not the solution).

Help me find the way, please.

mosquito commented 2 years ago

And I think that's it:


def main() -> None:
    connection = await aio_pika.connect()
    async with connection:
        channel = await connection.channel()
        ...

asyncio.run(main())
mosquito commented 2 years ago

Actually, __del__ creates the asyncio task with .close(), but it's not a guarantee, cause event loop might be closed before.