logoalt Hacker News

enragedcactitoday at 5:45 PM1 replyview on HN

> Like, why can't my sync function await something asynchronous?

The answer, at least for Python, is that it is an intentional limitation because the alternatives introduce some quite bad trade-offs.

Option 1: your awaited promise goes into the main async event loop. This is bad because it means that your single-threaded sync function now needs to be thread-safe, and so does any sync code that calls your sync function despite it not even knowing that you're doing anything async. This is essentially unworkable without throwing away the option of writing non-thread-safe code.

Option 2: Your awaited promise goes into its own new event loop that only contains sibling and child promises. There's nothing technically stopping someone from doing this[1], but now you've lost a ton of the value of async because you will inevitably end up with a ton of siloed event loops that leave the process idle despite other async tasks existing that could run. Effective async code needs to share an event loop at as high of a level as possible, which means tainting as many methods with async as possible. At that point, you might as well enforce it at the language level and avoid the inevitable pain and fragmentation that comes from other devs across the ecosystem mixing sync and async code.

[1] https://pypi.org/project/nest-asyncio/

As explained by Guido: https://github.com/python/cpython/issues/66435#issuecomment-...


Replies

zokiertoday at 6:05 PM

I think the downsides of option 2 are overstated here. In lots of cases you don't care about the "value of async", you just want code that works well enough and option 2 does accomplish that in anything that is not perf critical.

show 1 reply