Rodrigo Bernardo Pimentel: A first look at asyncio
Rodrigo Bernardo Pimentel gives us a first look at asyncio, at PyGrunn.
See the PyGrunn website for more info about this one-day Python conference in Groningen, The Netherlands.
Rodrigo is backend developer and team lead at Layar. That is an app that for example pops up a video when you point it at a certain page in a magazine.
asyncio was introduced about two months ago in Python 3.4. Also available on PyPI for 3.3, which is the bare minimum, because it uses yield from.
At Layar we already use some form of asynchronous IO. We have about 175k scans per day, so images that people scanned with their app. 85k publishers. We use Twisted, and some Tornado, on Python 2.7. We have been looking for excuses to start using Python 3.
asyncio is PEP-3156. It replaces asyncore. It is not meant to replace Twisted or Tornado, it just takes some experience from those packages.
asyncio has:
- coroutines, futures and tasks
- event loop
- transport, protocols
Coroutines replace callbacks. Give a task and a callback to call when the task is finished.
Futures are objects that will eventually have a result. You can yield from futures.
Tasks are a subclass of Future. It is a coroutine wrapped in a Future. As soon as you create the tasks, it starts running until it comes to a point where it has to wait. It does not wait for you to call .next() on the code that uses the task.
Event loop: it is Twisted-like. You can use it to call a function soon, later, or at a specific time. A loop can run forever or run until a certain task is completed.
Transports represent a connection. Typically implemented by a framework.
Protocols represent an application. Typically implemented by you.