2

I have a callback called by a third-party library.

def callback(message):
    print(message)

And I want to be able to do something like:

async for message in SomeIterator():
    print(message)

I know I can do it using asyncio.Queue like in Converting a Python function with a callback to an asyncio awaitable

The problem is that I can not properly clean up because there is no "exit" method for the async iterator. So there is no place for me to remove callback. The garbage collector will not collect my generator object because someone stores a reference to its callback method, so I can not use __del__ method also.

  • I'm a bit confused on the correlation between the two code snippets, but if the generator being kept alive is an issue you could try closing it. – Numerlor Feb 03 '22 at 17:35
  • There's `__aexit__` magic method for an async iterator. Is this what you're looking for? – Mikhail Gerasimov Feb 03 '22 at 17:36
  • Presumably you run() the third-party library and it calls your callback and you want to do something else as well. Perhaps you need your own event-loop, implement your callback to add to a queue and run the third-party library in a subprocess. – jwal Feb 05 '22 at 17:17
  • Does the library that call the callback tell you when it is done, i.e. when no more callbacks will be invoked? – user4815162342 Feb 05 '22 at 21:26

0 Answers0