SlideShare a Scribd company logo
1 of 39
Download to read offline
19 Dec 2013
@lukmdo

Python Asynchronous I/O
asynchronous landscape refresher

Photo by Jake Brown used under CC BY 2.0/“Mono+Balance”
Agenda ⏰10 minutes
!

•

Background (can skip)

•

Problem statement

•

“Current state”

•

Python 3 async horizon (by examples)
Warmup
!

•

CPU IO (CPU bound)

•

Pure IO (IO bound)

•

C10k

•

Concurrency vs. parallelism
Warmup
!

•

Lazy schedule a task for later

•

Avoid waiting for IO (i.e. 2x DB queries)

•

Solve embarrassingly parallel problems

•

Control and manage status of task
PEP index brief
PEP

Name

Status

Doc

PEP 255

Simple Generators

2.2 ✔

»»

PEP 342

Coroutines via Enhanced Generators

2.5 ✔

»

PEP 380

Syntax for Delegating to a Subgenerator

3.3 ✔

»

PEP 3148

Futures - execute computations asynchronously

3.2 ✔

»

PEP 3153

Asynchronous IO support

3.3 ✔

»

PEP 3156

Asynchronous IO Support Rebooted: the
"asyncio" Module

3.4 ✔

»
PEP index brief
PEP

Name

PEP 219

Stackless Python

❙❙

PEP 220

Coroutines, Generators, Continuations

✗

PEP 319

Python Synchronize/Asynchronize Block

✗

PEP 3145
PEP 3152

Asynchronous I/O For subprocess.Popen
Cofunctions

Status

❙❙
❙❙
stackless

In the Class
concurrent.futures
threading
tornado
greenlet
subpocess
eventlet
celery
twisted
pyuv
gevent
shed asyncio
asyncore
In the Class

asyncio
stackless

In the Class
concurrent.futures
threading
tornado
greenlet
subpocess
eventlet
celery
twisted
pyuv
gevent
shed asyncio
asyncore
In the Class
concurrent.futures
threading
tornado
subpocess
celery
twisted
asyncio
Slang*
•

future ~ result wrapper

•

coro != generator function (but close)

•

task = coro wrapped in Future

•

result = yield from future/coro
(to wait for result)
new* old style concurrency
def update_foo(data):
data1 = run_query1(data)
data2 = run_query2(data)
!

data3 = process(data1, data2)
run_update_query(data3)
run_update_cache(data3)
!

return ["OK"]
new* old style concurrency
def update_foo(data):
data1 = run_query1(data)
data2 = run_query2(data)
!

data3 = process(data1, data2)
run_update_query(data3)
run_update_cache(data3)
!

return ["OK"]
new* old style concurrency
new* old style concurrency
new* old style concurrency
@asyncio.coroutine
def update_foo(data, loop):
data1 = yield from run_query1(data)
data2 = yield from run_query2(data)
!

data3 = yield from process(data1, data2)
yield from run_update_query(data3)
loop.call_soon(update_cache, data3)
!

return ["OK"]
new* old style concurrency
@asyncio.coroutine
def update_foo(data, loop):
data1 = yield from run_query1(data)
data2 = yield from run_query2(data)
!

data3 = yield from process(data1, data2)
yield from run_update_query(data3)
loop.call_soon(update_cache, data3)
!

return ["OK"]
new* old style concurrency
@asyncio.coroutine
def update_foo(data, loop):
data1 = yield from run_query1(data)
data2 = yield from run_query2(data)
!

data3 = yield from process(data1, data2)
yield from run_update_query(data3)
loop.call_soon(update_cache, data3)
!

return ["OK"]
new* old style concurrency
new* old style concurrency
new* old style concurrency
new* old style concurrency
@asyncio.coroutine
def update_foo(data, loop):
future1 = asyncio.async(run_query1(data))
future2 = asyncio.async(run_query2(data))
!

results = yield from asyncio.gather(
future1, future2)
data3 = yield from process(*results)
yield from run_update_query(data3)
!

loop.call_soon(update_cache, data3)
!

return ["OK"]
new* old style concurrency
@asyncio.coroutine
def update_foo(data, loop):
future1 = asyncio.async(run_query1(data))
future2 = asyncio.async(run_query2(data))
!

results = yield from asyncio.gather(
future1, future2)
data3 = yield from process(*results)
yield from run_update_query(data3)
!

loop.call_soon(update_cache, data3)
!

return ["OK"]
new* old style concurrency
@asyncio.coroutine
def update_foo(data, loop):
future1 = asyncio.async(run_query1(data))
future2 = asyncio.async(run_query2(data))
!

results = yield from asyncio.gather(
future1, future2)
data3 = yield from process(*results)
yield from run_update_query(data3)
!

loop.call_soon(update_cache, data3)
!

return ["OK"]
new* old style concurrency
new* old style concurrency
new* old style concurrency
new* old style concurrency
def api_calls():
data1 = call_api1()
data2 = call_api2()
data3 = call_api3()
!

return [data1, data2, data3]
new* old style concurrency
def api_calls():
data1 = call_api1()
data3 = call_api2()
data3 = call_api3()
!

return [data1, data2, data3]
new* old style concurrency
new* old style concurrency
new* old style concurrency
@asyncio.coroutine
def api_calls():
future1 = asyncio.Task(call_api1())
future2 = asyncio.Task(call_api2())
future3 = asyncio.Task(call_api3())
!

return ( yield from asyncio.gather(
future1, future2, future3) )
new* old style concurrency
@asyncio.coroutine
def api_calls():
future1 = asyncio.Task(call_api1())
future2 = asyncio.Task(call_api2())
future3 = asyncio.Task(call_api3())
!

return ( yield from asyncio.gather(
future1, future2, future3) )
new* old style concurrency
new* old style concurrency
new* old style concurrency
new* old style concurrency
from aiohttp import request
!

@asyncio.coroutine
def call_api():
url = "URL"
response = yield from request('GET', url)
return (yield from response.read())
Takeaways
•

concurrency patterns

•

asyncio bootstrap

•

early adopters
Links
•

Video by BDFL Tulip: Async I/O for Python 3

•

Video by BDFL PyCon US 2013 Keynote

•

Code by Nikolay Kim aiohttp

•

Code by google appengine-pipeline

•

Code by google ndb tasklets

Photo by Jake Brown used under CC BY 2.0/“Mono+Tile”

More Related Content

What's hot

Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
Ankur Gupta
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
Abed Bukhari
 

What's hot (20)

Something about Golang
Something about GolangSomething about Golang
Something about Golang
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Future
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in Gecko
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
 
Use C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in GeckoUse C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in Gecko
 
Understanding greenlet
Understanding greenletUnderstanding greenlet
Understanding greenlet
 
Don't do this
Don't do thisDon't do this
Don't do this
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in Rust
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Rust
RustRust
Rust
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
 

Viewers also liked

Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with gevent
Mahendra M
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
Jim Yeh
 

Viewers also liked (20)

Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Python Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and GeventPython Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and Gevent
 
asyncio community, one year later
asyncio community, one year laterasyncio community, one year later
asyncio community, one year later
 
LvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncioLvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncio
 
Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with gevent
 
Asynchronous I/O in Python 3
Asynchronous I/O in Python 3Asynchronous I/O in Python 3
Asynchronous I/O in Python 3
 
Tulip
TulipTulip
Tulip
 
Faster Python, FOSDEM
Faster Python, FOSDEMFaster Python, FOSDEM
Faster Python, FOSDEM
 
Python on Rails 2014
Python on Rails 2014Python on Rails 2014
Python on Rails 2014
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
 
Python class
Python classPython class
Python class
 
Comandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocerComandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocer
 
Python master class 3
Python master class 3Python master class 3
Python master class 3
 
Practical continuous quality gates for development process
Practical continuous quality gates for development processPractical continuous quality gates for development process
Practical continuous quality gates for development process
 
Async Tasks with Django Channels
Async Tasks with Django ChannelsAsync Tasks with Django Channels
Async Tasks with Django Channels
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4
 
Regexp
RegexpRegexp
Regexp
 
What is the best full text search engine for Python?
What is the best full text search engine for Python?What is the best full text search engine for Python?
What is the best full text search engine for Python?
 
Python as number crunching code glue
Python as number crunching code gluePython as number crunching code glue
Python as number crunching code glue
 
Building social network with Neo4j and Python
Building social network with Neo4j and PythonBuilding social network with Neo4j and Python
Building social network with Neo4j and Python
 

Similar to Python Async IO Horizon

Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...
Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...
Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...
Flink Forward
 
AWR, ADDM, ASH, Metrics and Advisors.ppt
AWR, ADDM, ASH, Metrics and Advisors.pptAWR, ADDM, ASH, Metrics and Advisors.ppt
AWR, ADDM, ASH, Metrics and Advisors.ppt
bugzbinny
 

Similar to Python Async IO Horizon (20)

Golang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyGolang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war story
 
Automating with NX-OS: Let's Get Started!
Automating with NX-OS: Let's Get Started!Automating with NX-OS: Let's Get Started!
Automating with NX-OS: Let's Get Started!
 
Insomniac Physics
Insomniac PhysicsInsomniac Physics
Insomniac Physics
 
Reproducible Computational Pipelines with Docker and Nextflow
Reproducible Computational Pipelines with Docker and NextflowReproducible Computational Pipelines with Docker and Nextflow
Reproducible Computational Pipelines with Docker and Nextflow
 
What you need to know for postgresql operation
What you need to know for postgresql operationWhat you need to know for postgresql operation
What you need to know for postgresql operation
 
Using AWR for IO Subsystem Analysis
Using AWR for IO Subsystem AnalysisUsing AWR for IO Subsystem Analysis
Using AWR for IO Subsystem Analysis
 
Apache Flink: Better, Faster & Uncut - Piotr Nowojski, data Artisans
Apache Flink: Better, Faster & Uncut - Piotr Nowojski, data ArtisansApache Flink: Better, Faster & Uncut - Piotr Nowojski, data Artisans
Apache Flink: Better, Faster & Uncut - Piotr Nowojski, data Artisans
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
Diving into Delta Lake: Unpacking the Transaction Log
Diving into Delta Lake: Unpacking the Transaction LogDiving into Delta Lake: Unpacking the Transaction Log
Diving into Delta Lake: Unpacking the Transaction Log
 
Data Structures: Stack Operations
Data Structures:    Stack OperationsData Structures:    Stack Operations
Data Structures: Stack Operations
 
State Management in Apache Flink : Consistent Stateful Distributed Stream Pro...
State Management in Apache Flink : Consistent Stateful Distributed Stream Pro...State Management in Apache Flink : Consistent Stateful Distributed Stream Pro...
State Management in Apache Flink : Consistent Stateful Distributed Stream Pro...
 
What’s new in 9.6, by PostgreSQL contributor
What’s new in 9.6, by PostgreSQL contributorWhat’s new in 9.6, by PostgreSQL contributor
What’s new in 9.6, by PostgreSQL contributor
 
(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...
(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...
(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...
 
Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...
Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...
Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...
 
AWR, ADDM, ASH, Metrics and Advisors.ppt
AWR, ADDM, ASH, Metrics and Advisors.pptAWR, ADDM, ASH, Metrics and Advisors.ppt
AWR, ADDM, ASH, Metrics and Advisors.ppt
 
Python 3
Python 3Python 3
Python 3
 
2021 10-13 i ox query processing
2021 10-13 i ox query processing2021 10-13 i ox query processing
2021 10-13 i ox query processing
 
InfluxDB IOx Tech Talks: Query Processing in InfluxDB IOx
InfluxDB IOx Tech Talks: Query Processing in InfluxDB IOxInfluxDB IOx Tech Talks: Query Processing in InfluxDB IOx
InfluxDB IOx Tech Talks: Query Processing in InfluxDB IOx
 
2015 bioinformatics bio_python
2015 bioinformatics bio_python2015 bioinformatics bio_python
2015 bioinformatics bio_python
 
CS6401 Operating systems - Solved Examples
CS6401 Operating systems - Solved ExamplesCS6401 Operating systems - Solved Examples
CS6401 Operating systems - Solved Examples
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Python Async IO Horizon

  • 1. 19 Dec 2013 @lukmdo Python Asynchronous I/O asynchronous landscape refresher Photo by Jake Brown used under CC BY 2.0/“Mono+Balance”
  • 2. Agenda ⏰10 minutes ! • Background (can skip) • Problem statement • “Current state” • Python 3 async horizon (by examples)
  • 3. Warmup ! • CPU IO (CPU bound) • Pure IO (IO bound) • C10k • Concurrency vs. parallelism
  • 4. Warmup ! • Lazy schedule a task for later • Avoid waiting for IO (i.e. 2x DB queries) • Solve embarrassingly parallel problems • Control and manage status of task
  • 5. PEP index brief PEP Name Status Doc PEP 255 Simple Generators 2.2 ✔ »» PEP 342 Coroutines via Enhanced Generators 2.5 ✔ » PEP 380 Syntax for Delegating to a Subgenerator 3.3 ✔ » PEP 3148 Futures - execute computations asynchronously 3.2 ✔ » PEP 3153 Asynchronous IO support 3.3 ✔ » PEP 3156 Asynchronous IO Support Rebooted: the "asyncio" Module 3.4 ✔ »
  • 6. PEP index brief PEP Name PEP 219 Stackless Python ❙❙ PEP 220 Coroutines, Generators, Continuations ✗ PEP 319 Python Synchronize/Asynchronize Block ✗ PEP 3145 PEP 3152 Asynchronous I/O For subprocess.Popen Cofunctions Status ❙❙ ❙❙
  • 11. Slang* • future ~ result wrapper • coro != generator function (but close) • task = coro wrapped in Future • result = yield from future/coro (to wait for result)
  • 12. new* old style concurrency def update_foo(data): data1 = run_query1(data) data2 = run_query2(data) ! data3 = process(data1, data2) run_update_query(data3) run_update_cache(data3) ! return ["OK"]
  • 13. new* old style concurrency def update_foo(data): data1 = run_query1(data) data2 = run_query2(data) ! data3 = process(data1, data2) run_update_query(data3) run_update_cache(data3) ! return ["OK"]
  • 14. new* old style concurrency
  • 15. new* old style concurrency
  • 16. new* old style concurrency @asyncio.coroutine def update_foo(data, loop): data1 = yield from run_query1(data) data2 = yield from run_query2(data) ! data3 = yield from process(data1, data2) yield from run_update_query(data3) loop.call_soon(update_cache, data3) ! return ["OK"]
  • 17. new* old style concurrency @asyncio.coroutine def update_foo(data, loop): data1 = yield from run_query1(data) data2 = yield from run_query2(data) ! data3 = yield from process(data1, data2) yield from run_update_query(data3) loop.call_soon(update_cache, data3) ! return ["OK"]
  • 18. new* old style concurrency @asyncio.coroutine def update_foo(data, loop): data1 = yield from run_query1(data) data2 = yield from run_query2(data) ! data3 = yield from process(data1, data2) yield from run_update_query(data3) loop.call_soon(update_cache, data3) ! return ["OK"]
  • 19. new* old style concurrency
  • 20. new* old style concurrency
  • 21. new* old style concurrency
  • 22. new* old style concurrency @asyncio.coroutine def update_foo(data, loop): future1 = asyncio.async(run_query1(data)) future2 = asyncio.async(run_query2(data)) ! results = yield from asyncio.gather( future1, future2) data3 = yield from process(*results) yield from run_update_query(data3) ! loop.call_soon(update_cache, data3) ! return ["OK"]
  • 23. new* old style concurrency @asyncio.coroutine def update_foo(data, loop): future1 = asyncio.async(run_query1(data)) future2 = asyncio.async(run_query2(data)) ! results = yield from asyncio.gather( future1, future2) data3 = yield from process(*results) yield from run_update_query(data3) ! loop.call_soon(update_cache, data3) ! return ["OK"]
  • 24. new* old style concurrency @asyncio.coroutine def update_foo(data, loop): future1 = asyncio.async(run_query1(data)) future2 = asyncio.async(run_query2(data)) ! results = yield from asyncio.gather( future1, future2) data3 = yield from process(*results) yield from run_update_query(data3) ! loop.call_soon(update_cache, data3) ! return ["OK"]
  • 25. new* old style concurrency
  • 26. new* old style concurrency
  • 27. new* old style concurrency
  • 28. new* old style concurrency def api_calls(): data1 = call_api1() data2 = call_api2() data3 = call_api3() ! return [data1, data2, data3]
  • 29. new* old style concurrency def api_calls(): data1 = call_api1() data3 = call_api2() data3 = call_api3() ! return [data1, data2, data3]
  • 30. new* old style concurrency
  • 31. new* old style concurrency
  • 32. new* old style concurrency @asyncio.coroutine def api_calls(): future1 = asyncio.Task(call_api1()) future2 = asyncio.Task(call_api2()) future3 = asyncio.Task(call_api3()) ! return ( yield from asyncio.gather( future1, future2, future3) )
  • 33. new* old style concurrency @asyncio.coroutine def api_calls(): future1 = asyncio.Task(call_api1()) future2 = asyncio.Task(call_api2()) future3 = asyncio.Task(call_api3()) ! return ( yield from asyncio.gather( future1, future2, future3) )
  • 34. new* old style concurrency
  • 35. new* old style concurrency
  • 36. new* old style concurrency
  • 37. new* old style concurrency from aiohttp import request ! @asyncio.coroutine def call_api(): url = "URL" response = yield from request('GET', url) return (yield from response.read())
  • 39. Links • Video by BDFL Tulip: Async I/O for Python 3 • Video by BDFL PyCon US 2013 Keynote • Code by Nikolay Kim aiohttp • Code by google appengine-pipeline • Code by google ndb tasklets Photo by Jake Brown used under CC BY 2.0/“Mono+Tile”