Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Daniel Arbuckle???s Mastering Python

You're reading from   Daniel Arbuckle???s Mastering Python Build powerful Python applications

Arrow left icon
Product type Paperback
Published in Jun 2017
Publisher Packt
ISBN-13 9781787283695
Length 274 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Daniel Arbuckle Daniel Arbuckle
Author Profile Icon Daniel Arbuckle
Daniel Arbuckle
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Title Page
Credits
About the Author
www.PacktPub.com
Customer Feedback
Preface
1. Python Primer FREE CHAPTER 2. Setting Up 3. Making a Package 4. Basic Best Practices 5. Making a Command-Line Utility 6. Parallel Processing 7. Coroutines and Asynchronous I/O 8. Metaprogramming 9. Unit Testing 10. Reactive Programming 11. Microservices 12. Extension Modules and Compiled Code

Using the asyncio event loop and coroutine scheduler


So far, you have learned about Python's coroutines and a bit about how a cooperative coroutine scheduler works. Now, let's try our hand at writing some asynchronous code using Python coroutines and asyncio. We start this by creating a coroutine.

Creating a coroutine

It's easy to create a coroutine—all we have to do is use the async keyword on a function and use await anytime we want to call other coroutines, as shown in following code example:

Once we have a coroutine though, we can't just call it to get the ball rolling. If we try to call it, it immediately returns a coroutine object, as shown in the following code example—that's not much use:

Instead, we need to add the coroutine to the asyncio's scheduler as a new task. Next, the scheduler runs arranging for coroutines to execute and handling input and output events.

The asyncio scheduler - event_loop

The asyncio package automatically creates a default scheduler, also called event_loop...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime
Visually different images