Python for the .NET developer Transcripts
Chapter: async and await in Python
Lecture: Converting to unsync
0:00 Happy days are here because we get to use unsync
0:03 to make this much better and much closer to C#'s version
0:06 but we got to add unsync as a dependency here.
0:10 We'll go ahead and let that get installed.
0:12 Say it's spelled correctly as well.
0:14 This library is incredibly simple.
0:16 It's one single Python file that's only 126 lines long
0:20 however, it does a lot of magic.
0:22 So let's import unsync from unsync import unsync.
0:27 This is the library, this is the decorator.
0:29 Okay, this business about the loop
0:31 that we juggled directly, forget it.
0:33 We don't need that anymore.
0:35 This stuff about running until complete, forget it.
0:37 We don't need that anymore.
0:39 What we're going to do is we're going to say result.
0:41 It's not there yet cause I haven't added
0:42 the right change to it.
0:44 Stuff about running until it's done and then closing
0:46 that's all gone. That's nice, right?
0:49 The trade off we got to do is we have to say
0:51 that these are unsync methods, not regular methods.
0:55 Not regular asynchronous methods, but unsync.
0:59 And what that means is unsync basically manages
1:02 the run time for it.
1:03 From this line onward, oh stay still.
1:06 From here onward, it's unchanged.
1:08 You just write regular Async IO code.
1:13 Down here, again, we have an async method
1:15 so we're going to say unsync on it
1:17 and this loop create task blah, blah, blah, forget that.
1:20 Call it like a function
1:22 like it was meant to be, like it is in C#
1:24 you call the function.
1:25 It automatically starts and runs.
1:28 It's glorious. And that's it.
1:30 All the stuff about juggling the loop
1:32 creating the task, running to complete
1:34 all of that is gone. And let me go back up here
1:37 this get titles, I think it doesn't quite get the type hint
1:42 that this is what's called an unfuture that comes back
1:44 but I think it's going to run. Let's run it.
1:47 This is basically wait for it to be finished.
1:50 All right, let's go. It's running. It's done.
1:54 Boom. It ran in 1.08 seconds.
1:58 That is super cool. And what work did we do?
2:02 Not very much.
2:03 We just stopped doing all the Async IO junk.
2:06 And we just put this one decorator
2:08 on the asynchronous methods.
2:11 Run again, done. Run it again, done.
2:15 Whoo, look at that, we broke sub second time
2:19 yeah, that is so, so sweet.
2:23 We got this working really, really well
2:25 and we were able to use unsync to do that.