I am trying to create some kind of timer callback for the bound async method using the asyncio event asyncio . Now the problem is that the associated asynchronous method should not contain a strong reference to the instance, otherwise the latter will never be deleted. The timer callback should only work up to the parent instance. I found a solution, but I do not think it is beautiful:
import asyncio import functools import weakref class ClassWithTimer: def __init__(self): asyncio.ensure_future( functools.partial( ClassWithTimer.update, weakref.ref(self) )() ) def __del__(self): print("deleted ClassWithTimer!") async def update(self): while True: await asyncio.sleep(1) if self() is None: break print("IN update of object " + repr(self())) async def run(): foo = ClassWithTimer() await asyncio.sleep(5) del foo loop = asyncio.get_event_loop() loop.run_until_complete(run())
Is there a better, more pythonic way to do this? The timer callback really needs to be asynchronous. Without asyncio , weakref.WeakMethod probably be the way to go. But asyncio.ensure_future requires an accompanying object, so in this case it will not work.
python timer weak-references python-asyncio
pumphaus
source share