SlideShare une entreprise Scribd logo
1  sur  39
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 

Dernier (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

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