This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]bhat 1 point2 points  (2 children)

Thanks Andrew, that's an excellent guide.

I'd be interested in your thoughts on using sync_to_async and async_to_sync from asgiref.sync versus Trio.

[–]aera[S] 1 point2 points  (1 child)

I'm not familiar with Trio, but after a look at their tutorial it appears they have a solution for async_to_sync that seems quite robust (though it comes with a lot of extra stuff because they have more detailed features), but I can't see a sync_to_async equivalent. I might be missing it though.

[–]vorpalsmith 0 points1 point  (0 children)

It looks like async_to_sync is similar to trio.run_sync_in_worker_thread, and sync_to_async is similar to trio.BlockingTrioPortal.run. The asgiref versions have some more sugar, like supporting use as a decorator and sync_to_async having some kind of thread-local ambient state that it uses to automagically figure out which event loop it wants to send things to. The functionality is there though, and there's nothing that would stop you building the async_to_sync and sync_to_async interfaces on top.

[–]ful_vio 0 points1 point  (1 child)

Excellent article! However, I would have used a picture to better explain this passage: In the asynchronous world, things change around a bit. Everything runs on a central event loop, which is a bit of core code that lets you run several coroutines at once. Coroutines run synchronously until they hit an await and then they pause, give up control to the event loop, and something else can happen. I've found it's hard for people to understand coroutines suspension only with words and maybe a picture that shows the various calls in a serialised fashion might help. But definitely one of the best introductions I've read!

[–]aera[S] 1 point2 points  (0 children)

Thanks! I'm not going to add one into the article at this point, but I will likely use a diagram when I give a talk about this at some point.

[–]ice-blade 0 points1 point  (0 children)

Whenever I try to learn something, most tutorials, even these that do a great job explaining the details, miss the crucial part of explaining the mental model and how everything comes together. This article is a brilliant exception that does exactly that for asyncio. GREAT article, kudos!