SlideShare a Scribd company logo
1 of 39
Download to read offline
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 LispDamien Cassou
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistAnton Arhipov
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinAndrey Breslav
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrencyjgrahamc
 
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 JavassistAnton Arhipov
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practiceGuilherme Garnier
 
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&CoMail.ru Group
 
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 kotlinAhmad Arif Faizin
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architectureJung 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 ComeCory 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

Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windowsextremecoders
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance PythonIan Ozsvald
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonOdessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonMax Klymyshyn
 
Beyond tf idf why, what & how
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & howlucenerevolution
 
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 projectsLinkurious
 
Introduction to Apache Accumulo
Introduction to Apache AccumuloIntroduction to Apache Accumulo
Introduction to Apache AccumuloAaron 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 AMBARIDataWorks 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
 
The art of_being_healthy
The art of_being_healthyThe art of_being_healthy
The art of_being_healthyChandan Dubey
 
Social media worthy sites for educators
Social media worthy sites for educatorsSocial media worthy sites for educators
Social media worthy sites for educatorsMaryMorrisCMS
 

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 GolangBo-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 RxJavaFrank Lyaruu
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan 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éesRomain Lecomte
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and InferenceRichard Fox
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in GolangOliver 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 RemotingKnoldus Inc.
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2Zaar 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.0Oscar 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 themFilipe Ximenes
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewDmytro 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 fruitVaclav Pech
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio Zoppi
 
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 MongoDBemptysquare
 

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

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 

Recently uploaded (20)

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 

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