SlideShare a Scribd company logo
Python, do 
you even 
async? 
Saúl Ibarra Corretgé 
@saghul 
DomCode, August 2014
repr(self) 
>>> from Amsterdam import saghul 
>>> 
>>> saghul.work() 
VoIP, SIP, XMPP, chat, Real Time Communications 
>>> 
>>> saghul.other() 
networking, event loops, sockets, MOAR PYTHON 
>>> 
>>> saghul.languages() 
Python, C 
>>>
github.com/saghul
Please give feedback! 
https://joind.in/event/view/2471
The road to 
asynchronous i/o
import socket 
import socket 
! 
server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) 
server.bind(('127.0.0.1', 1234)) 
server.listen(511) 
print("Server listening on: {}".format(server.getsockname())) 
! 
client, addr = server.accept() 
print("Client connected: {}".format(addr)) 
! 
while True: 
data = client.recv(4096) 
if not data: 
print("Client has disconnected") 
break 
client.send(data) 
! 
server.close()
except Exception: 
• We can only handle one client at a time! 
• Solutions for handling multiple clients 
• Threads 
• I/O multiplexing 
• Check the C10K problem if you haven’t 
already! 
• http://www.kegel.com/c10k.html
try: sockets + threads 
import socket 
import thread 
! 
def handle_client(client, addr): 
print("Client connected: {}".format(addr)) 
while True: 
data = client.recv(4096) 
if not data: 
print("Client has disconnected") 
break 
client.send(data.upper()) 
! 
server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) 
server.bind(('127.0.0.1', 1234)) 
server.listen(511) 
print("Server listening on: {}".format(server.getsockname())) 
! 
while True: 
client, addr = server.accept() 
thread.start_new_thread(handle_client, (client, addr))
except Exception: 
• Threads have overhead 
• Stack size 
• Context switching 
• Synchronisation 
• GIL? 
• Not for I/O!
I/O multiplexing 
• Examine and block for I/O in multiple 
file descriptors at the same time 
• Single thread 
• A file descriptor is ready if the 
corresponding I/O operation can be 
performed without blocking 
• File descriptor has to be set to be 
non-blocking
I/O is hard 
• Different paradigms in Unix vs 
Windows 
• “are you ready?” vs “call me later” 
• Frameworks 
• Abstract platform differences 
• Provide tools for easier development of 
applications
Python, do you even async?
The included batteries 
• select 
• asyncore / asyncchat 
• selectors 
• asyncio
“batteries don’t fit” 
http://bit.ly/182HcHT
Frameworks 
• Platform abstraction 
• Protocol implementations 
• Integration with other event loops: Qt, 
GLib, ... 
• Different API styles 
• Async file i/o?
import twisted 
• Uses select, poll, kqueue, epoll from 
the select module 
• IOCP on Windows 
• Integration with other event loops 
• Factory / Protocol / Transport 
abstractions 
• Deferreds
import tornado 
• Uses select, poll, kqueue, epoll from 
the select module 
• select() on Windows :-( 
• Mainly oriented to web development 
• Synchronous looking API with 
coroutines / Futures
import gevent 
• Uses libev for platform abstraction 
• select() on Windows :-( 
• Syncronous API using greenlet 
• ME LIKEY! :-)
Solution!
I’m not trying to reinvent the 
wheel. I’m trying to build a 
good one. 
! 
Guido van Rossum
asyncio 
import tulip
import asyncio 
• Reference implementation for 
PEP-3156 
• Basic components for doing async i/o 
• Works on Python >= 3.3 
• Trollius: backport for Python >= 2.6
Goals 
• Modern implementation of asynchronous 
i/o for Python 
• Use yield from (PEP-380) 
• But don’t force it 
• Don’t use anything that requires 
Python > 3.3 
• Interoperability with other frameworks
Goals 
• Unix and Windows support 
• IPv4 and IPv6 
• TCP, UDP and pipes 
• Basic SSL (secure by default) 
• Subprocesses
Non goals 
• Perfection 
• Replacing current frameworks 
• Protocol implementations 
• Replace httplib, smtplib, ... 
• Make it work on Python < 3.3
Interoperability 
twisted tornado gevent ... 
asyncio 
selectors iocp
Example: Tornado 
tornado 
asyncio / twisted 
tornado 
epoll/kqueue
Architecture
Components 
Event loop, policy 
Coroutines, Futures, Tasks 
Transports, Protocols, Streams
Calculate 
poll time Poll 
Run 
callbacks 
Event loop
Event loop & policy 
• Chooses the best i/o mechanism for a 
given platform 
• APIs for creating server and client 
connections (TCP, UDP, …) 
• Establish the context for a loop
Working with threads 
• loop.call_soon_threadsafe(func, *args) 
• loop.run_in_executor(exc, func, *args) 
• loop.set_default_executor(exc) 
! 
• PEP-3148 executor
Coroutines, Futures & 
Tasks
Coroutines, Futures & Tasks 
• Coroutines 
• a generator function, can receive values 
• decorated with @coroutine 
• Future 
• promise of a result or an error 
• Task 
• Future which runs a coroutine
Coroutines & yield from 
import asyncio 
import socket 
! 
loop = asyncio.get_event_loop() 
! 
@asyncio.coroutine 
def handle_client(client, addr): 
print("Client connected: {}".format(addr)) 
while True: 
data = yield from loop.sock_recv(client, 4096) 
if not data: 
print("Client has disconnected") 
break 
client.send(data) 
! 
@asyncio.coroutine 
def accept_connections(server_socket): 
while True: 
client, addr = yield from loop.sock_accept(server_socket) 
asyncio.async(handle_client(client, addr)) 
! 
server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) 
server.bind(('127.0.0.1', 1234)) 
server.listen(511) 
server.setblocking(False) 
print("Server listening on: {}".format(server.getsockname())) 
! 
loop.run_until_complete(accept_connections(server))
Coroutines & yield from 
• Imagine the yield from is not there 
• Imagine the code is executed 
sequentially 
• Not exactly the formal definition of yield 
from (from PEP-380)
Futures 
• Similar to Futures from PEP-3148 
• API (almost) identical 
• Adapted for asyncio’s single threaded 
model
Futures + Coroutines 
• yield from works with Futures! 
• f = Future() 
• Someone will set the result or exception 
• r = yield from f 
• Waits until done and returns f.result() 
• Usually returned by functions
Undoing callbacks (I) 
@asyncio.coroutine 
def sync_looking_function(*args): 
fut = asyncio.Future() 
def cb(result, error): 
if error is not None: 
fut.set_result(result) 
else: 
fut.set_exception(Exception(error)) 
async_function(cb, *args) 
return (yield from fut)
Undoing callbacks (II) 
! 
def sync_looking_function(*args): 
fut = asyncio.Future() 
def cb(result, error): 
if error is not None: 
fut.set_result(result) 
else: 
fut.set_exception(Exception(error)) 
async_function(cb, *args) 
return fut
Tasks 
• Unicorns covered in fairy dust 
• It’s a coroutine wrapped in a Future 
• Inherits from Future 
• Works with yield from 
• r = yield from Task(coro(...))
Tasks vs coroutines 
• A coroutine doesn’t “advance” without 
a scheduling mechanism 
• Tasks can advance in their own 
• The event loop is the scheduler!
Example 
import asyncio 
! 
loop = asyncio.get_event_loop() 
clients = {} # task -> (reader, writer) 
! 
def accept_client(client_reader, client_writer): 
task = asyncio.Task(handle_client(client_reader, client_writer)) 
clients[task] = (client_reader, client_writer) 
! 
def client_done(task): 
del clients[task] 
! 
task.add_done_callback(client_done) 
! 
@asyncio.coroutine 
def handle_client(client_reader, client_writer): 
while True: 
data = (yield from client_reader.readline()) 
client_writer.write(data) 
!! 
f = asyncio.start_server(accept_client, '127.0.0.1', 12345) 
server = loop.run_until_complete(f) 
loop.run_forever()
Transports & Protocols
Transports & Protocols 
• Transport: represents a connection 
(socket, pipe, ...) 
• Protocol: represents an application 
(HTTP server, IRC client, ...) 
• They always go together 
• API is based on function calls and 
callbacks
Streams 
• Abstraction on top of transports / 
protocols 
• File-like API using coroutines
Transport -> Protocol 
• connection_made(transport) 
• data_received(data) 
• eof_received() 
• connection_lost(exc) 
! 
• UDP, pipes and subprocesses are slightly 
different
Protocol -> Transport 
• write(data) 
• writelines(seq) 
• write_eof() 
• close()
Enter Trollius! 
• Backport of asyncio for Python >= 2.6 
• By Victor Stinner (@haypo) 
• Slightly different syntax 
• yield instead of yield from 
• raise Return(x) instead of return x on 
generators 
• pip install trollius
That was all?! 
• Go read PEP-3156 
• Implement a simple protocol (an IRC 
client for example) 
• Checkout the links on the last slide 
• Use asyncio in your next project
Questions? 
@saghul 
bettercallsaghul.com
Links 
• https://code.google.com/p/tulip/ 
• http://legacy.python.org/dev/peps/ 
pep-3156/ 
• https://code.google.com/p/tulip/wiki/ 
ThirdParty 
• http://asyncio.org/ 
• http://www.slideshare.net/saghul

More Related Content

What's hot (20)

PDF
Concurrency in Python
Mosky Liu
 
PDF
Tornadoweb
Osman Yuksel
 
PPTX
Tornado web
kurtiss
 
KEY
Introduction to node.js
jacekbecela
 
PDF
Event loop
codepitbull
 
PPTX
Python, async web frameworks, and MongoDB
emptysquare
 
KEY
Non blocking io with netty
Zauber
 
PDF
Asynchronous I/O in Python 3
Feihong Hsu
 
PDF
Oredev 2015 - Taming Java Agents
Anton Arhipov
 
PPTX
Async await
Jeff Hart
 
PDF
Vert.x clustering on Docker, CoreOS and ETCD
Tim Nolet
 
PDF
Of Owls and IO Objects
Felix Morgner
 
PDF
Treasure Data Summer Internship Final Report
Ritta Narita
 
PPTX
Tornado - different Web programming
Dima Malenko
 
KEY
PyCon AU 2012 - Debugging Live Python Web Applications
Graham Dumpleton
 
PPTX
Bucks County Tech Meetup: node.js introduction
dshkolnikov
 
PDF
Deep Dive async/await in Unity with UniTask(EN)
Yoshifumi Kawai
 
PPTX
Coroutines talk ppt
Shahroz Khan
 
PPTX
Lua: the world's most infuriating language
jgrahamc
 
PPTX
Async and Await on the Server
Doug Jones
 
Concurrency in Python
Mosky Liu
 
Tornadoweb
Osman Yuksel
 
Tornado web
kurtiss
 
Introduction to node.js
jacekbecela
 
Event loop
codepitbull
 
Python, async web frameworks, and MongoDB
emptysquare
 
Non blocking io with netty
Zauber
 
Asynchronous I/O in Python 3
Feihong Hsu
 
Oredev 2015 - Taming Java Agents
Anton Arhipov
 
Async await
Jeff Hart
 
Vert.x clustering on Docker, CoreOS and ETCD
Tim Nolet
 
Of Owls and IO Objects
Felix Morgner
 
Treasure Data Summer Internship Final Report
Ritta Narita
 
Tornado - different Web programming
Dima Malenko
 
PyCon AU 2012 - Debugging Live Python Web Applications
Graham Dumpleton
 
Bucks County Tech Meetup: node.js introduction
dshkolnikov
 
Deep Dive async/await in Unity with UniTask(EN)
Yoshifumi Kawai
 
Coroutines talk ppt
Shahroz Khan
 
Lua: the world's most infuriating language
jgrahamc
 
Async and Await on the Server
Doug Jones
 

Viewers also liked (20)

PDF
Python Async IO Horizon
Lukasz Dobrzanski
 
PDF
Python Performance: Single-threaded, multi-threaded, and Gevent
emptysquare
 
PDF
Understanding greenlet
Saúl Ibarra Corretgé
 
PDF
Scaling Django with gevent
Mahendra M
 
PDF
Vert.x – The problem of real-time data binding
Alex Derkach
 
PDF
Dive into Python Class
Jim Yeh
 
PDF
Faster Python, FOSDEM
Victor Stinner
 
PDF
Python on Rails 2014
Albert O'Connor
 
PDF
Python class
건희 김
 
TXT
Comandos para ubuntu 400 que debes conocer
Geek Advisor Freddy
 
PDF
Python master class 3
Chathuranga Bandara
 
PPTX
Building microservices with vert.x 3.0
Agraj Mangal
 
PDF
Practical continuous quality gates for development process
Andrii Soldatenko
 
PPTX
The Awesome Python Class Part-4
Binay Kumar Ray
 
PDF
Async Tasks with Django Channels
Albert O'Connor
 
PDF
Regexp
Ynon Perek
 
PDF
What is the best full text search engine for Python?
Andrii Soldatenko
 
PDF
Python as number crunching code glue
Jiahao Chen
 
PDF
Building social network with Neo4j and Python
Andrii Soldatenko
 
PDF
Async Web Frameworks in Python
Ryan Johnson
 
Python Async IO Horizon
Lukasz Dobrzanski
 
Python Performance: Single-threaded, multi-threaded, and Gevent
emptysquare
 
Understanding greenlet
Saúl Ibarra Corretgé
 
Scaling Django with gevent
Mahendra M
 
Vert.x – The problem of real-time data binding
Alex Derkach
 
Dive into Python Class
Jim Yeh
 
Faster Python, FOSDEM
Victor Stinner
 
Python on Rails 2014
Albert O'Connor
 
Python class
건희 김
 
Comandos para ubuntu 400 que debes conocer
Geek Advisor Freddy
 
Python master class 3
Chathuranga Bandara
 
Building microservices with vert.x 3.0
Agraj Mangal
 
Practical continuous quality gates for development process
Andrii Soldatenko
 
The Awesome Python Class Part-4
Binay Kumar Ray
 
Async Tasks with Django Channels
Albert O'Connor
 
Regexp
Ynon Perek
 
What is the best full text search engine for Python?
Andrii Soldatenko
 
Python as number crunching code glue
Jiahao Chen
 
Building social network with Neo4j and Python
Andrii Soldatenko
 
Async Web Frameworks in Python
Ryan Johnson
 
Ad

Similar to Python, do you even async? (20)

PDF
asyncio internals
Saúl Ibarra Corretgé
 
PDF
The journey of asyncio adoption in instagram
Jimmy Lai
 
PDF
Introduction to Python Asyncio
Nathan Van Gheem
 
PDF
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
Mykola Novik
 
PDF
Asynchronous Python A Gentle Introduction
PyData
 
PDF
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Pôle Systematic Paris-Region
 
PDF
Webscraping with asyncio
Jose Manuel Ortega Candel
 
PDF
Python meetup: coroutines, event loops, and non-blocking I/O
Buzzcapture
 
PDF
Twisted
Michal Sedlak
 
PDF
Async I/O in Python
Python Ireland
 
PDF
What Is Async, How Does It Work, And When Should I Use It?
emptysquare
 
PDF
Digging into asyncio
MinJeong Kim
 
PDF
Python concurrency: libraries overview
Andrii Mishkovskyi
 
PPTX
Asynchronous programming with django
bangaloredjangousergroup
 
PDF
Asynchronous Python and You
AddShoppers
 
PDF
Python Coroutines, Present and Future
emptysquare
 
PDF
Python, WebRTC and You (v2)
Saúl Ibarra Corretgé
 
PDF
Tulip
Jose Galarza
 
PDF
asyncio community, one year later
Victor Stinner
 
PPTX
Understanding concurrency
Anshul Sharma
 
asyncio internals
Saúl Ibarra Corretgé
 
The journey of asyncio adoption in instagram
Jimmy Lai
 
Introduction to Python Asyncio
Nathan Van Gheem
 
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
Mykola Novik
 
Asynchronous Python A Gentle Introduction
PyData
 
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Pôle Systematic Paris-Region
 
Webscraping with asyncio
Jose Manuel Ortega Candel
 
Python meetup: coroutines, event loops, and non-blocking I/O
Buzzcapture
 
Twisted
Michal Sedlak
 
Async I/O in Python
Python Ireland
 
What Is Async, How Does It Work, And When Should I Use It?
emptysquare
 
Digging into asyncio
MinJeong Kim
 
Python concurrency: libraries overview
Andrii Mishkovskyi
 
Asynchronous programming with django
bangaloredjangousergroup
 
Asynchronous Python and You
AddShoppers
 
Python Coroutines, Present and Future
emptysquare
 
Python, WebRTC and You (v2)
Saúl Ibarra Corretgé
 
asyncio community, one year later
Victor Stinner
 
Understanding concurrency
Anshul Sharma
 
Ad

More from Saúl Ibarra Corretgé (20)

PDF
JanusCon 2024: Mom there are robots in my meeting
Saúl Ibarra Corretgé
 
PDF
Challenges running Jitsi Meet at scale during the pandemic
Saúl Ibarra Corretgé
 
PDF
The Road to End-to-End Encryption in Jitsi Meet
Saúl Ibarra Corretgé
 
PDF
Jitsi: State of the Union 2020
Saúl Ibarra Corretgé
 
PDF
Jitsi Meet: our tale of blood, sweat, tears and love
Saúl Ibarra Corretgé
 
PDF
Jitsi Meet: Video conferencing for the privacy minded
Saúl Ibarra Corretgé
 
PDF
Jitsi - Estado de la unión 2019
Saúl Ibarra Corretgé
 
PDF
Get a room! Spot: the ultimate physical meeting room experience
Saúl Ibarra Corretgé
 
PDF
Going Mobile with React Native and WebRTC
Saúl Ibarra Corretgé
 
PDF
Going Mobile with React Native and WebRTC
Saúl Ibarra Corretgé
 
PDF
Jitsi: Estado de la Unión (2018)
Saúl Ibarra Corretgé
 
PDF
Jitsi: state-of-the-art video conferencing you can self-host
Saúl Ibarra Corretgé
 
PDF
WebRTC: El epicentro de la videoconferencia y IoT
Saúl Ibarra Corretgé
 
PDF
Jitsi: Open Source Video Conferencing
Saúl Ibarra Corretgé
 
PDF
Jitsi: State of the Union
Saúl Ibarra Corretgé
 
PDF
libuv: cross platform asynchronous i/o
Saúl Ibarra Corretgé
 
PDF
Videoconferencias: el santo grial de WebRTC
Saúl Ibarra Corretgé
 
PDF
SylkServer: State of the art RTC application server
Saúl Ibarra Corretgé
 
PDF
Escalabilidad horizontal desde las trincheras
Saúl Ibarra Corretgé
 
PDF
A deep dive into libuv
Saúl Ibarra Corretgé
 
JanusCon 2024: Mom there are robots in my meeting
Saúl Ibarra Corretgé
 
Challenges running Jitsi Meet at scale during the pandemic
Saúl Ibarra Corretgé
 
The Road to End-to-End Encryption in Jitsi Meet
Saúl Ibarra Corretgé
 
Jitsi: State of the Union 2020
Saúl Ibarra Corretgé
 
Jitsi Meet: our tale of blood, sweat, tears and love
Saúl Ibarra Corretgé
 
Jitsi Meet: Video conferencing for the privacy minded
Saúl Ibarra Corretgé
 
Jitsi - Estado de la unión 2019
Saúl Ibarra Corretgé
 
Get a room! Spot: the ultimate physical meeting room experience
Saúl Ibarra Corretgé
 
Going Mobile with React Native and WebRTC
Saúl Ibarra Corretgé
 
Going Mobile with React Native and WebRTC
Saúl Ibarra Corretgé
 
Jitsi: Estado de la Unión (2018)
Saúl Ibarra Corretgé
 
Jitsi: state-of-the-art video conferencing you can self-host
Saúl Ibarra Corretgé
 
WebRTC: El epicentro de la videoconferencia y IoT
Saúl Ibarra Corretgé
 
Jitsi: Open Source Video Conferencing
Saúl Ibarra Corretgé
 
Jitsi: State of the Union
Saúl Ibarra Corretgé
 
libuv: cross platform asynchronous i/o
Saúl Ibarra Corretgé
 
Videoconferencias: el santo grial de WebRTC
Saúl Ibarra Corretgé
 
SylkServer: State of the art RTC application server
Saúl Ibarra Corretgé
 
Escalabilidad horizontal desde las trincheras
Saúl Ibarra Corretgé
 
A deep dive into libuv
Saúl Ibarra Corretgé
 

Recently uploaded (20)

PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 

Python, do you even async?

  • 1. Python, do you even async? Saúl Ibarra Corretgé @saghul DomCode, August 2014
  • 2. repr(self) >>> from Amsterdam import saghul >>> >>> saghul.work() VoIP, SIP, XMPP, chat, Real Time Communications >>> >>> saghul.other() networking, event loops, sockets, MOAR PYTHON >>> >>> saghul.languages() Python, C >>>
  • 4. Please give feedback! https://joind.in/event/view/2471
  • 5. The road to asynchronous i/o
  • 6. import socket import socket ! server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) server.bind(('127.0.0.1', 1234)) server.listen(511) print("Server listening on: {}".format(server.getsockname())) ! client, addr = server.accept() print("Client connected: {}".format(addr)) ! while True: data = client.recv(4096) if not data: print("Client has disconnected") break client.send(data) ! server.close()
  • 7. except Exception: • We can only handle one client at a time! • Solutions for handling multiple clients • Threads • I/O multiplexing • Check the C10K problem if you haven’t already! • http://www.kegel.com/c10k.html
  • 8. try: sockets + threads import socket import thread ! def handle_client(client, addr): print("Client connected: {}".format(addr)) while True: data = client.recv(4096) if not data: print("Client has disconnected") break client.send(data.upper()) ! server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) server.bind(('127.0.0.1', 1234)) server.listen(511) print("Server listening on: {}".format(server.getsockname())) ! while True: client, addr = server.accept() thread.start_new_thread(handle_client, (client, addr))
  • 9. except Exception: • Threads have overhead • Stack size • Context switching • Synchronisation • GIL? • Not for I/O!
  • 10. I/O multiplexing • Examine and block for I/O in multiple file descriptors at the same time • Single thread • A file descriptor is ready if the corresponding I/O operation can be performed without blocking • File descriptor has to be set to be non-blocking
  • 11. I/O is hard • Different paradigms in Unix vs Windows • “are you ready?” vs “call me later” • Frameworks • Abstract platform differences • Provide tools for easier development of applications
  • 13. The included batteries • select • asyncore / asyncchat • selectors • asyncio
  • 14. “batteries don’t fit” http://bit.ly/182HcHT
  • 15. Frameworks • Platform abstraction • Protocol implementations • Integration with other event loops: Qt, GLib, ... • Different API styles • Async file i/o?
  • 16. import twisted • Uses select, poll, kqueue, epoll from the select module • IOCP on Windows • Integration with other event loops • Factory / Protocol / Transport abstractions • Deferreds
  • 17. import tornado • Uses select, poll, kqueue, epoll from the select module • select() on Windows :-( • Mainly oriented to web development • Synchronous looking API with coroutines / Futures
  • 18. import gevent • Uses libev for platform abstraction • select() on Windows :-( • Syncronous API using greenlet • ME LIKEY! :-)
  • 20. I’m not trying to reinvent the wheel. I’m trying to build a good one. ! Guido van Rossum
  • 22. import asyncio • Reference implementation for PEP-3156 • Basic components for doing async i/o • Works on Python >= 3.3 • Trollius: backport for Python >= 2.6
  • 23. Goals • Modern implementation of asynchronous i/o for Python • Use yield from (PEP-380) • But don’t force it • Don’t use anything that requires Python > 3.3 • Interoperability with other frameworks
  • 24. Goals • Unix and Windows support • IPv4 and IPv6 • TCP, UDP and pipes • Basic SSL (secure by default) • Subprocesses
  • 25. Non goals • Perfection • Replacing current frameworks • Protocol implementations • Replace httplib, smtplib, ... • Make it work on Python < 3.3
  • 26. Interoperability twisted tornado gevent ... asyncio selectors iocp
  • 27. Example: Tornado tornado asyncio / twisted tornado epoll/kqueue
  • 29. Components Event loop, policy Coroutines, Futures, Tasks Transports, Protocols, Streams
  • 30. Calculate poll time Poll Run callbacks Event loop
  • 31. Event loop & policy • Chooses the best i/o mechanism for a given platform • APIs for creating server and client connections (TCP, UDP, …) • Establish the context for a loop
  • 32. Working with threads • loop.call_soon_threadsafe(func, *args) • loop.run_in_executor(exc, func, *args) • loop.set_default_executor(exc) ! • PEP-3148 executor
  • 34. Coroutines, Futures & Tasks • Coroutines • a generator function, can receive values • decorated with @coroutine • Future • promise of a result or an error • Task • Future which runs a coroutine
  • 35. Coroutines & yield from import asyncio import socket ! loop = asyncio.get_event_loop() ! @asyncio.coroutine def handle_client(client, addr): print("Client connected: {}".format(addr)) while True: data = yield from loop.sock_recv(client, 4096) if not data: print("Client has disconnected") break client.send(data) ! @asyncio.coroutine def accept_connections(server_socket): while True: client, addr = yield from loop.sock_accept(server_socket) asyncio.async(handle_client(client, addr)) ! server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) server.bind(('127.0.0.1', 1234)) server.listen(511) server.setblocking(False) print("Server listening on: {}".format(server.getsockname())) ! loop.run_until_complete(accept_connections(server))
  • 36. Coroutines & yield from • Imagine the yield from is not there • Imagine the code is executed sequentially • Not exactly the formal definition of yield from (from PEP-380)
  • 37. Futures • Similar to Futures from PEP-3148 • API (almost) identical • Adapted for asyncio’s single threaded model
  • 38. Futures + Coroutines • yield from works with Futures! • f = Future() • Someone will set the result or exception • r = yield from f • Waits until done and returns f.result() • Usually returned by functions
  • 39. Undoing callbacks (I) @asyncio.coroutine def sync_looking_function(*args): fut = asyncio.Future() def cb(result, error): if error is not None: fut.set_result(result) else: fut.set_exception(Exception(error)) async_function(cb, *args) return (yield from fut)
  • 40. Undoing callbacks (II) ! def sync_looking_function(*args): fut = asyncio.Future() def cb(result, error): if error is not None: fut.set_result(result) else: fut.set_exception(Exception(error)) async_function(cb, *args) return fut
  • 41. Tasks • Unicorns covered in fairy dust • It’s a coroutine wrapped in a Future • Inherits from Future • Works with yield from • r = yield from Task(coro(...))
  • 42. Tasks vs coroutines • A coroutine doesn’t “advance” without a scheduling mechanism • Tasks can advance in their own • The event loop is the scheduler!
  • 43. Example import asyncio ! loop = asyncio.get_event_loop() clients = {} # task -> (reader, writer) ! def accept_client(client_reader, client_writer): task = asyncio.Task(handle_client(client_reader, client_writer)) clients[task] = (client_reader, client_writer) ! def client_done(task): del clients[task] ! task.add_done_callback(client_done) ! @asyncio.coroutine def handle_client(client_reader, client_writer): while True: data = (yield from client_reader.readline()) client_writer.write(data) !! f = asyncio.start_server(accept_client, '127.0.0.1', 12345) server = loop.run_until_complete(f) loop.run_forever()
  • 45. Transports & Protocols • Transport: represents a connection (socket, pipe, ...) • Protocol: represents an application (HTTP server, IRC client, ...) • They always go together • API is based on function calls and callbacks
  • 46. Streams • Abstraction on top of transports / protocols • File-like API using coroutines
  • 47. Transport -> Protocol • connection_made(transport) • data_received(data) • eof_received() • connection_lost(exc) ! • UDP, pipes and subprocesses are slightly different
  • 48. Protocol -> Transport • write(data) • writelines(seq) • write_eof() • close()
  • 49. Enter Trollius! • Backport of asyncio for Python >= 2.6 • By Victor Stinner (@haypo) • Slightly different syntax • yield instead of yield from • raise Return(x) instead of return x on generators • pip install trollius
  • 50. That was all?! • Go read PEP-3156 • Implement a simple protocol (an IRC client for example) • Checkout the links on the last slide • Use asyncio in your next project
  • 52. Links • https://code.google.com/p/tulip/ • http://legacy.python.org/dev/peps/ pep-3156/ • https://code.google.com/p/tulip/wiki/ ThirdParty • http://asyncio.org/ • http://www.slideshare.net/saghul