H
H
Helow192742018-08-28 16:59:24
Python
Helow19274, 2018-08-28 16:59:24

How to make an asynchronous destructor?

There is a class. It creates aiohttp.ClientSession. This session is actively used in methods.
How to make __del__ close the session?
As far as I know this function cannot be asynchronous.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2018-08-28
@dmtrrr

https://docs.python.org/3/reference/datamodel.html...
Called when the instance is about to be destroyed. This is also called a finalizer or ( improperly ) a destructor.
The general recommendation is not to use this method.

L
lega, 2018-08-30
@lega

This hack works with 3.6+, aclose will be called when the loop closes

import asyncio

class Test():
    async def aclose(self):
        print('hook during close')

test = Test()

async def main():
    asyncio.get_event_loop()._asyncgen_firstiter_hook(test)
    await asyncio.sleep(1)

asyncio.run(main())

Another option, CancelledError occurs when the loop stops, then you can call your code
import asyncio

async def main():
    print('start')

    async def on_stop():
        try:
            await asyncio.sleep(10**10)
        except asyncio.CancelledError:
            pass
        print('stopping start')
        await asyncio.sleep(1)
        print('stopping end')
    asyncio.ensure_future(on_stop())

    await asyncio.sleep(1)

asyncio.run(main())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question