14 Advanced asyncio

 

This chapter covers

  • Designing APIs for both coroutines and functions
  • Coroutine context locals
  • Yielding to the event loop
  • Using different event loop implementations
  • The relationship between coroutines and generators
  • Creating your own event loop with custom awaitables

We’ve learned the vast majority of what asyncio has to offer. Using the modules of asyncio covered in previous chapters, you should be able to complete almost any task you need. That said, there are still a few lesser-known techniques that you may need to use, especially if you’re designing your own asyncio APIs.

In this chapter, we’ll learn a smorgasbord of more advanced techniques available in asyncio. We’ll learn how to design APIs that can handle both coroutines and regular Python functions, how to force iterations of the event loop, and how to pass state between tasks without ever passing arguments. We’ll also dig into more details on how exactly asyncio uses generators to fully understand what is happening under the hood. We’ll do this by implementing our own custom awaitables and using them to build our own simple implementation of an event loop that can run multiple coroutines concurrently.

14.1 APIs with coroutines and functions

14.2 Context variables

14.3 Forcing an event loop iteration

14.4 Using different event loop implementations

14.5 Creating a custom event loop

14.5.1 Coroutines and generators

14.5.2 Generator-based coroutines are deprecated

14.5.3 Custom awaitables

14.5.4 Using sockets with futures

14.5.5 A task implementation

14.5.6 Implementing an event loop

14.5.7 Implementing a server with a custom event loop

Summary