SlideShare a Scribd company logo
Python Coroutines
Present and Future
    A. Jesse Jiryu Davis
  http://emptysquare.net
           10gen
Python Coroutines
     Present and Future
    Agenda:

•   Coroutines are wonderful for async
•   …but weird.
•   Understanding the weirdness.
•   Coroutine Kung Fu.
•   The Future!
Coroutines are
wonderful for async
Async with callback
from tornado.web import RequestHandler

class AsyncHandler(RequestHandler):
    @asynchronous
    def get(self):
        http_client = AsyncHTTPClient()
        http_client.fetch(
            "http://example.com",
            callback=self.on_fetch)

    def on_fetch(self, response):
        do_something_with_response(response)
        self.render("template.html")
Async with coroutine

from tornado.web import RequestHandler

class GenAsyncHandler(RequestHandler):
    @asynchronous
    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch(
            "http://example.com")
        do_something_with_response(response)
        self.render("template.html")
Async with coroutine

from tornado.web import RequestHandler

class GenAsyncHandler(RequestHandler):
    @asynchronous
    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        future = http_client.fetch(
            "http://example.com")
        response = yield future
        do_something_with_response(response)
        self.render("template.html")
Agenda:

• Coroutines are wonderful for Async I/O
• …but weird.

  • yield
  • future
  • coroutine
yield
def make_generator():
    yield 0
    yield 1

g = make_generator()
print(g)
# <generator object make_generator
at 0x1006b4b40>
def make_generator():
    yield 0
    yield 1

g = make_generator()
for i in g:
    print(i)
def make_generator():
    yield 0
    yield 1

g = make_generator()
while True:
    try:
         i = g.__next__()
         print(i)
    except StopIteration:
         break
def make_generator():
    yield 0
    yield 1

g = make_generator()
while True:
    try:
         i = g.send(None)
         print(i)
    except StopIteration:
         break
Prints:
def make_generator():
    return_value = yield 0
                                    0
    print 'got', return_value       got 10
    return_value = yield 1          1
    print 'got', return_value       got 11

g = make_generator()
i = g.send(None) # Start g
while True:
    try:
         print(i)
         i = g.send(i + 10)
    except StopIteration:
         break
Agenda:

• Coroutines are wonderful for Async I/O
• …but weird.

  • yield
  • future
  • coroutine
Future
class GenAsyncHandler(RequestHandler):
    @asynchronous
    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        future = http_client.fetch(
            "http://example.com")
        response = yield future
        do_something_with_response(response)
        self.render("template.html")
future = Future()

future.done()   # False

future.set_result('foo')

future.set_exception(
    SomeException('error message'))

future.add_done_callback(callback)

# Return result or raise error
future.result()
class GenAsyncHandler(RequestHandler):
    @asynchronous
    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        future = http_client.fetch(
            "http://example.com")
        response = yield future
        do_something_with_response(response)
        self.render("template.html")
Agenda:

• Coroutines are wonderful for Async I/O
• …but weird.

  • yield
  • future
  • coroutine
# part of the Tornado framework

class Runner(object):
    def __init__(self, make_generator):
        self.gen = make_generator()
        # Starts done, with result None
        self.future = NullFuture()
class Runner(object):
    # ...                                "recurse"
    def run(self):
        while True:
            if not self.future.done():
                self.future.add_done_callback(self.run)
                return

            value = self.future.result()

            try:
                self.future = self.gen.send(value)
            except (StopIteration, Return) as e:
                return
class GenAsyncHandler(RequestHandler):
    @asynchronous
    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        future = http_client.fetch(
            "http://example.com")
        response = yield future
        do_something_with_response(response)
        self.render("template.html")
Agenda:

• Coroutines are wonderful for Async I/O
• …but weird.
• Handling the weirdness.
@gen.coroutine
def print_code():
    response = yield get('http://example.com')
    print response.code

@gen.coroutine                 weird
def get(url):
    client = AsyncHTTPClient()
    response = yield client.fetch(url)
    raise gen.Return(response)

print_code()
@gen.coroutine
def print_code():
    future = get('http://example.com')
    response = yield future
    print response.code

@gen.coroutine
def get(url):
    client = AsyncHTTPClient()
    response = yield client.fetch(url)
    raise gen.Return(response)

print_code()
                      weird
Python 3.3
@gen.coroutine
def print_code():
    future = get('http://example.com')
    response = yield future
    print response.code

@gen.coroutine
def get(url):
    client = AsyncHTTPClient()
    response = yield client.fetch(url)
    return response

print_code()
                       normal
@gen.coroutine
def print_code():
    try:
         code = yield get('http://example.com')
         print code
    except HTTPError, e:      normal
         print e

@gen.coroutine
def get(url):
    client = AsyncHTTPClient()
    response = yield client.fetch(url)
    raise gen.Return(response.code)

print_code()
Agenda:

•   Coroutines are wonderful for Async I/O
•   …but weird.
•   Handling the weirdness.
•   Coroutine Kung Fu.
Fan-out
@gen.coroutine
def f():
    client = AsyncHTTPClient()
    responses = yield [
         client.fetch('http://mongodb.org'),
         client.fetch('http://10gen.com')]

      print responses

f()
Fan-out

@gen.coroutine
def f():
    client = AsyncHTTPClient()
    future0 = client.fetch('http://mongodb.org')
    future1 = client.fetch('http://10gen.com')
    responses = yield [future0, future1]
    print responses

f()
Toro




Synchronization Primitives for
    Tornado Coroutines
event = toro.Event()

@gen.coroutine
def waiter():
    print "I'll wait right here"
    yield event.wait() # Yield a Future
    print "I'm done waiting"

@gen.coroutine
def setter():
    print "About to set"
    event.set()
    print "Done setting"

waiter()
setter()
q = toro.Queue(maxsize=3)

@gen.coroutine
def producer():
    for item in range(5):
        print 'Sending', item
        yield q.put(item)

@gen.coroutine
def consumer():
    while True:
        item = yield q.get()
        print 'tt', 'Got', item

consumer()
producer()
$ python producer_consumer.py
Sending 0
       ! ! Got 0
Sending 1
       ! ! Got 1
Sending 2
       ! ! Got 2
Sending 3
       ! ! Got 3
Sending 4
       ! ! Got 4
Agenda:

•   Coroutines are wonderful for Async I/O
•   …but weird.
•   Handling the weirdness.
•   Kung Fu.
•   The Future!
Tulip

• A standard event loop

• A standard coroutine library

• For inclusion in Python 3.4
yield from
@gen.coroutine
def print_code():                     Tornado
    response = yield get('http://example.com')
    print response.code

@gen.coroutine
def get(url):
    client = AsyncHTTPClient()
    response = yield client.fetch(url)
    raise gen.Return(response)

@tulip.coroutine
def print_code():
                                       Tulip
    response = yield from get('http://example.com')
    print(response.status)

@tulip.coroutine
                               "yield from"
def get(url):
    request = tulip.http.request('GET', url)
    response = yield from request
    return response
                          normal return
Guido
          on
"The Difference Between
  yield and yield-from":

http://bit.ly/yieldfrom
q = tulip.queues.Queue(maxsize=3)

@tulip.coroutine
def producer():
    for item in range(5):
        print('Sending', item)
        yield from q.put(item)

@tulip.coroutine
def consumer():
    while True:
        item = yield from q.get()
        print('tt', 'Got', item)

Task(consumer())
Task(producer())
StopIteration
   A. Jesse Jiryu Davis
 http://emptysquare.net
          10gen

More Related Content

What's hot

Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
Damien Cassou
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
Lukasz Dobrzanski
 
Rust
RustRust
The future of async i/o in Python
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in Python
Saúl Ibarra Corretgé
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
Anton Arhipov
 
node ffi
node ffinode ffi
node ffi
偉格 高
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
Andrey Breslav
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
jgrahamc
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
Saúl Ibarra Corretgé
 
Introduction to asyncio
Introduction to asyncioIntroduction to asyncio
Introduction to asyncio
Saúl Ibarra Corretgé
 
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
Anton Arhipov
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practice
Guilherme Garnier
 
Golang Channels
Golang ChannelsGolang Channels
Golang Channels
Joris Bonnefoy
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
Brendan Eich
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
Nikita Popov
 
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
Mail.ru Group
 
Understanding greenlet
Understanding greenletUnderstanding greenlet
Understanding greenlet
Saúl Ibarra Corretgé
 
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlin
Ahmad Arif Faizin
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architecture
Jung Kim
 
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
Cory Forsyth
 

What's hot (20)

Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
 
Rust
RustRust
Rust
 
The future of async i/o in Python
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in Python
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
 
node ffi
node ffinode ffi
node ffi
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Introduction to asyncio
Introduction to asyncioIntroduction to asyncio
Introduction to asyncio
 
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
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practice
 
Golang Channels
Golang ChannelsGolang Channels
Golang Channels
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
 
Understanding greenlet
Understanding greenletUnderstanding greenlet
Understanding greenlet
 
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlin
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architecture
 
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
 

Viewers also liked

Faster Python
Faster PythonFaster Python
Faster Python
Anoop Thomas Mathew
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
extremecoders
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
Ian Ozsvald
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonOdessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and Python
Max Klymyshyn
 
Beyond tf idf why, what & how
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & how
lucenerevolution
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101Ankur Gupta
 
Inside the ANN: A visual and intuitive journey to understand how artificial n...
Inside the ANN: A visual and intuitive journey to understand how artificial n...Inside the ANN: A visual and intuitive journey to understand how artificial n...
Inside the ANN: A visual and intuitive journey to understand how artificial n...
XavierArrufat
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 
Kick start graph visualization projects
Kick start graph visualization projectsKick start graph visualization projects
Kick start graph visualization projects
Linkurious
 
Introduction to Apache Accumulo
Introduction to Apache AccumuloIntroduction to Apache Accumulo
Introduction to Apache Accumulo
Aaron Cordova
 
Deploying and Managing Hadoop Clusters with AMBARI
Deploying and Managing Hadoop Clusters with AMBARIDeploying and Managing Hadoop Clusters with AMBARI
Deploying and Managing Hadoop Clusters with AMBARI
DataWorks Summit
 
Tues factors of production
Tues factors of productionTues factors of production
Tues factors of productionTravis Klein
 
Day 9 westward expansion, women religion
Day 9 westward expansion, women religionDay 9 westward expansion, women religion
Day 9 westward expansion, women religionTravis Klein
 
Dsc
DscDsc
Dsc
ianil
 
սուրբ գեվորգ
սուրբ գեվորգսուրբ գեվորգ
սուրբ գեվորգ
tatevabrahamyan
 
The art of_being_healthy
The art of_being_healthyThe art of_being_healthy
The art of_being_healthy
Chandan Dubey
 
Social media worthy sites for educators
Social media worthy sites for educatorsSocial media worthy sites for educators
Social media worthy sites for educators
MaryMorrisCMS
 

Viewers also liked (20)

Faster Python
Faster PythonFaster Python
Faster Python
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonOdessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and Python
 
Beyond tf idf why, what & how
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & how
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
 
Inside the ANN: A visual and intuitive journey to understand how artificial n...
Inside the ANN: A visual and intuitive journey to understand how artificial n...Inside the ANN: A visual and intuitive journey to understand how artificial n...
Inside the ANN: A visual and intuitive journey to understand how artificial n...
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
Kick start graph visualization projects
Kick start graph visualization projectsKick start graph visualization projects
Kick start graph visualization projects
 
Introduction to Apache Accumulo
Introduction to Apache AccumuloIntroduction to Apache Accumulo
Introduction to Apache Accumulo
 
Deploying and Managing Hadoop Clusters with AMBARI
Deploying and Managing Hadoop Clusters with AMBARIDeploying and Managing Hadoop Clusters with AMBARI
Deploying and Managing Hadoop Clusters with AMBARI
 
Flip book
Flip bookFlip book
Flip book
 
Thur child labor
Thur child laborThur child labor
Thur child labor
 
Tues factors of production
Tues factors of productionTues factors of production
Tues factors of production
 
Day 9 westward expansion, women religion
Day 9 westward expansion, women religionDay 9 westward expansion, women religion
Day 9 westward expansion, women religion
 
Dsc
DscDsc
Dsc
 
սուրբ գեվորգ
սուրբ գեվորգսուրբ գեվորգ
սուրբ գեվորգ
 
Law of supply
Law of supplyLaw of supply
Law of supply
 
The art of_being_healthy
The art of_being_healthyThe art of_being_healthy
The art of_being_healthy
 
Social media worthy sites for educators
Social media worthy sites for educatorsSocial media worthy sites for educators
Social media worthy sites for educators
 

Similar to Python Coroutines, Present and Future

Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
Bo-Yi Wu
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
Frank Lyaruu
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
Chetan Giridhar
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de données
Romain Lecomte
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
Richard Fox
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
Oliver N
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-people
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
Knoldus Inc.
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
Zaar Hai
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
Oscar Renalias
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
Filipe Ximenes
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
Dmytro Zaitsev
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
New in php 7
New in php 7New in php 7
New in php 7
Vic Metcalfe
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
Giorgio Zoppi
 
Current State of Coroutines
Current State of CoroutinesCurrent State of Coroutines
Current State of Coroutines
Guido Pio Mariotti
 
Architecture Patterns in Practice with Kotlin. UA Mobile 2017.
Architecture Patterns in Practice with Kotlin. UA Mobile 2017.Architecture Patterns in Practice with Kotlin. UA Mobile 2017.
Architecture Patterns in Practice with Kotlin. UA Mobile 2017.
UA Mobile
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
emptysquare
 

Similar to Python Coroutines, Present and Future (20)

Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Un dsl pour ma base de données
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de données
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 
New in php 7
New in php 7New in php 7
New in php 7
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
Current State of Coroutines
Current State of CoroutinesCurrent State of Coroutines
Current State of Coroutines
 
Architecture Patterns in Practice with Kotlin. UA Mobile 2017.
Architecture Patterns in Practice with Kotlin. UA Mobile 2017.Architecture Patterns in Practice with Kotlin. UA Mobile 2017.
Architecture Patterns in Practice with Kotlin. UA Mobile 2017.
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
 

Recently uploaded

PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 

Recently uploaded (20)

PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 

Python Coroutines, Present and Future

  • 1. Python Coroutines Present and Future A. Jesse Jiryu Davis http://emptysquare.net 10gen
  • 2. Python Coroutines Present and Future Agenda: • Coroutines are wonderful for async • …but weird. • Understanding the weirdness. • Coroutine Kung Fu. • The Future!
  • 4. Async with callback from tornado.web import RequestHandler class AsyncHandler(RequestHandler): @asynchronous def get(self): http_client = AsyncHTTPClient() http_client.fetch( "http://example.com", callback=self.on_fetch) def on_fetch(self, response): do_something_with_response(response) self.render("template.html")
  • 5. Async with coroutine from tornado.web import RequestHandler class GenAsyncHandler(RequestHandler): @asynchronous @gen.coroutine def get(self): http_client = AsyncHTTPClient() response = yield http_client.fetch( "http://example.com") do_something_with_response(response) self.render("template.html")
  • 6. Async with coroutine from tornado.web import RequestHandler class GenAsyncHandler(RequestHandler): @asynchronous @gen.coroutine def get(self): http_client = AsyncHTTPClient() future = http_client.fetch( "http://example.com") response = yield future do_something_with_response(response) self.render("template.html")
  • 7. Agenda: • Coroutines are wonderful for Async I/O • …but weird. • yield • future • coroutine
  • 8. yield def make_generator(): yield 0 yield 1 g = make_generator() print(g) # <generator object make_generator at 0x1006b4b40>
  • 9. def make_generator(): yield 0 yield 1 g = make_generator() for i in g: print(i)
  • 10. def make_generator(): yield 0 yield 1 g = make_generator() while True: try: i = g.__next__() print(i) except StopIteration: break
  • 11. def make_generator(): yield 0 yield 1 g = make_generator() while True: try: i = g.send(None) print(i) except StopIteration: break
  • 12. Prints: def make_generator(): return_value = yield 0 0 print 'got', return_value got 10 return_value = yield 1 1 print 'got', return_value got 11 g = make_generator() i = g.send(None) # Start g while True: try: print(i) i = g.send(i + 10) except StopIteration: break
  • 13. Agenda: • Coroutines are wonderful for Async I/O • …but weird. • yield • future • coroutine
  • 14. Future class GenAsyncHandler(RequestHandler): @asynchronous @gen.coroutine def get(self): http_client = AsyncHTTPClient() future = http_client.fetch( "http://example.com") response = yield future do_something_with_response(response) self.render("template.html")
  • 15. future = Future() future.done() # False future.set_result('foo') future.set_exception( SomeException('error message')) future.add_done_callback(callback) # Return result or raise error future.result()
  • 16. class GenAsyncHandler(RequestHandler): @asynchronous @gen.coroutine def get(self): http_client = AsyncHTTPClient() future = http_client.fetch( "http://example.com") response = yield future do_something_with_response(response) self.render("template.html")
  • 17. Agenda: • Coroutines are wonderful for Async I/O • …but weird. • yield • future • coroutine
  • 18. # part of the Tornado framework class Runner(object): def __init__(self, make_generator): self.gen = make_generator() # Starts done, with result None self.future = NullFuture()
  • 19. class Runner(object): # ... "recurse" def run(self): while True: if not self.future.done(): self.future.add_done_callback(self.run) return value = self.future.result() try: self.future = self.gen.send(value) except (StopIteration, Return) as e: return
  • 20. class GenAsyncHandler(RequestHandler): @asynchronous @gen.coroutine def get(self): http_client = AsyncHTTPClient() future = http_client.fetch( "http://example.com") response = yield future do_something_with_response(response) self.render("template.html")
  • 21. Agenda: • Coroutines are wonderful for Async I/O • …but weird. • Handling the weirdness.
  • 22. @gen.coroutine def print_code(): response = yield get('http://example.com') print response.code @gen.coroutine weird def get(url): client = AsyncHTTPClient() response = yield client.fetch(url) raise gen.Return(response) print_code()
  • 23. @gen.coroutine def print_code(): future = get('http://example.com') response = yield future print response.code @gen.coroutine def get(url): client = AsyncHTTPClient() response = yield client.fetch(url) raise gen.Return(response) print_code() weird
  • 24. Python 3.3 @gen.coroutine def print_code(): future = get('http://example.com') response = yield future print response.code @gen.coroutine def get(url): client = AsyncHTTPClient() response = yield client.fetch(url) return response print_code() normal
  • 25. @gen.coroutine def print_code(): try: code = yield get('http://example.com') print code except HTTPError, e: normal print e @gen.coroutine def get(url): client = AsyncHTTPClient() response = yield client.fetch(url) raise gen.Return(response.code) print_code()
  • 26. Agenda: • Coroutines are wonderful for Async I/O • …but weird. • Handling the weirdness. • Coroutine Kung Fu.
  • 27. Fan-out @gen.coroutine def f(): client = AsyncHTTPClient() responses = yield [ client.fetch('http://mongodb.org'), client.fetch('http://10gen.com')] print responses f()
  • 28. Fan-out @gen.coroutine def f(): client = AsyncHTTPClient() future0 = client.fetch('http://mongodb.org') future1 = client.fetch('http://10gen.com') responses = yield [future0, future1] print responses f()
  • 30. event = toro.Event() @gen.coroutine def waiter(): print "I'll wait right here" yield event.wait() # Yield a Future print "I'm done waiting" @gen.coroutine def setter(): print "About to set" event.set() print "Done setting" waiter() setter()
  • 31. q = toro.Queue(maxsize=3) @gen.coroutine def producer(): for item in range(5): print 'Sending', item yield q.put(item) @gen.coroutine def consumer(): while True: item = yield q.get() print 'tt', 'Got', item consumer() producer()
  • 32. $ python producer_consumer.py Sending 0 ! ! Got 0 Sending 1 ! ! Got 1 Sending 2 ! ! Got 2 Sending 3 ! ! Got 3 Sending 4 ! ! Got 4
  • 33. Agenda: • Coroutines are wonderful for Async I/O • …but weird. • Handling the weirdness. • Kung Fu. • The Future!
  • 34. Tulip • A standard event loop • A standard coroutine library • For inclusion in Python 3.4
  • 36. @gen.coroutine def print_code(): Tornado response = yield get('http://example.com') print response.code @gen.coroutine def get(url): client = AsyncHTTPClient() response = yield client.fetch(url) raise gen.Return(response) @tulip.coroutine def print_code(): Tulip response = yield from get('http://example.com') print(response.status) @tulip.coroutine "yield from" def get(url): request = tulip.http.request('GET', url) response = yield from request return response normal return
  • 37. Guido on "The Difference Between yield and yield-from": http://bit.ly/yieldfrom
  • 38. q = tulip.queues.Queue(maxsize=3) @tulip.coroutine def producer(): for item in range(5): print('Sending', item) yield from q.put(item) @tulip.coroutine def consumer(): while True: item = yield from q.get() print('tt', 'Got', item) Task(consumer()) Task(producer())
  • 39. StopIteration A. Jesse Jiryu Davis http://emptysquare.net 10gen