Python for .NET Developers Transcripts
Chapter: async and await in Python
Lecture: Converting to unsync

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Happy days are here because we get to use unsync to make this much better and much closer to C#'s version
0:07 but we got to add unsync as a dependency here. We'll go ahead and let that get installed. Say it's spelled correctly as well.
0:15 This library is incredibly simple. It's one single Python file that's only 126 lines long however, it does a lot of magic.
0:23 So let's import unsync from unsync import unsync. This is the library, this is the decorator. Okay, this business about the loop
0:32 that we juggled directly, forget it. We don't need that anymore. This stuff about running until complete, forget it. We don't need that anymore.
0:40 What we're going to do is we're going to say result. It's not there yet cause I haven't added the right change to it.
0:45 Stuff about running until it's done and then closing that's all gone. That's nice, right? The trade off we got to do is we have to say
0:52 that these are unsync methods, not regular methods. Not regular asynchronous methods, but unsync. And what that means is unsync basically manages
1:03 the run time for it. From this line onward, oh stay still. From here onward, it's unchanged. You just write regular Async IO code.
1:14 Down here, again, we have an async method so we're going to say unsync on it and this loop create task blah, blah, blah, forget that.
1:21 Call it like a function like it was meant to be, like it is in C# you call the function. It automatically starts and runs.
1:29 It's glorious. And that's it. All the stuff about juggling the loop creating the task, running to complete
1:35 all of that is gone. And let me go back up here this get titles, I think it doesn't quite get the type hint
1:43 that this is what's called an unfuture that comes back but I think it's going to run. Let's run it. This is basically wait for it to be finished.
1:51 All right, let's go. It's running. It's done. Boom. It ran in 1.08 seconds. That is super cool. And what work did we do? Not very much.
2:04 We just stopped doing all the Async IO junk. And we just put this one decorator on the asynchronous methods. Run again, done. Run it again, done.
2:16 Whoo, look at that, we broke sub second time yeah, that is so, so sweet. We got this working really, really well
2:26 and we were able to use unsync to do that.


Talk Python's Mastodon Michael Kennedy's Mastodon