My Python program is mostly async, but I have one critical third-party library that is purely synchronous and has a callback. I need to be able to use an async function as the callback (and just let it block, which is fine). I've tried a few ways and cannot get it to work properly.
from asgiref.sync import async_to_sync
from dataclasses import dataclass
from typing import Callable
import asyncio
# Third party library with synchronous callback.
# Library is not editable and cannot be made async.
@dataclass
class ThirdPartyLibrary:
callback: Callable[[str], None]
def run(self):
self.callback('hi')
# My callback to trigger; must be async
async def async_callback(x: str):
# E.g., write result to database; must be async
await asyncio.sleep(1)
print(x)
# My program that uses the third-party library.
# It's already running async, but uses ThirdPartyLibrary which is purely sync.
# How do I set my async_callback to be the callback for my library?
async def main():
third_party = ThirdPartyLibrary(callback=lambda x: async_to_sync(async_callback)(x)) # Doesn't work
third_party.run()
asyncio.run(main())