2 ms·
Depending on the details you can often call an async function from a sync function, by just running the event loop, it is just a few lines of code. The problem
by gpderetta 4y ago
Depending on the details you can often call an async function from a sync function, by just running the event loop, it is just a few lines of code.
The problem is that the event loop is not reentrant [1], so if your sync function is being called from an async function, things do not work. Why would you ever do this you might think? Well, asyncio might be an implementation detail of whatever environment you are using. Jupyiter or ipython for example.
[1] there are... hacks to make this sort of work of course.
- nineplay 4y ago> there are... hacks to make this sort of work of course. The python motto.
- gpderetta 4y agoMonkey patch like there is no tomorrow (so you do not have to maintain it)!
- quietbritishjim 4y agoAnother possibility, if it's a matter of passing callback parameter that must be sync where you wish it could be an async function, is that the callback can be the `put_nowait()` method of an async queue. You can then have a background async task that pulls from that queue and does async stuff. This works well if the callback is just there to notify you about a result (which is the most common case in fairness) but doesn't really work if the callback is meant to synchronously determine and return a result that is then used within the function that's calling the callback.
- gpderetta 4y agoYes, been there done that :). You can spawn a whole background thread running its own event loop, and post the async function with run-coroutine_threadsafe, the wait on the returned concurrent.future. But it feels wrong having to spawn a thread and event loop just for that.