Python Coroutines, Present and Future

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
1 of 39

Recommended

Python Yield by
Python YieldPython Yield
Python Yieldyangjuven
2.5K views88 slides
PyCon lightning talk on my Toro module for Tornado by
PyCon lightning talk on my Toro module for TornadoPyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for Tornadoemptysquare
4.5K views8 slides
Python meetup: coroutines, event loops, and non-blocking I/O by
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OBuzzcapture
2.7K views29 slides
Don't do this by
Don't do thisDon't do this
Don't do thisRichard Jones
86.7K views82 slides
A deep dive into PEP-3156 and the new asyncio module by
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleSaúl Ibarra Corretgé
15.2K views55 slides
Gevent what's the point by
Gevent what's the pointGevent what's the point
Gevent what's the pointseanmcq
6.9K views60 slides

More Related Content

What's hot

Metaprogramming and Reflection in Common Lisp by
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispDamien Cassou
5.6K views56 slides
Python Async IO Horizon by
Python Async IO HorizonPython Async IO Horizon
Python Async IO HorizonLukasz Dobrzanski
3.4K views39 slides
Rust by
RustRust
RustChih-Hsuan Kuo
845 views74 slides
The future of async i/o in Python by
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in PythonSaúl Ibarra Corretgé
6.1K views19 slides
JavaOne 2015 - Having fun with Javassist by
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistAnton Arhipov
1.9K views62 slides
node ffi by
node ffinode ffi
node ffi偉格 高
3K views152 slides

What's hot(20)

Metaprogramming and Reflection in Common Lisp by Damien Cassou
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
Damien Cassou5.6K views
JavaOne 2015 - Having fun with Javassist by Anton Arhipov
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
Anton Arhipov1.9K views
JVMLS 2016. Coroutines in Kotlin by Andrey Breslav
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
Andrey Breslav3K views
Go Concurrency by jgrahamc
Go ConcurrencyGo Concurrency
Go Concurrency
jgrahamc14.3K views
Riga Dev Day 2016 - Having fun with Javassist by Anton Arhipov
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
Anton Arhipov1.7K views
Proxies are Awesome! by Brendan Eich
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
Brendan Eich39.5K views
What's new in PHP 8.0? by Nikita Popov
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
Nikita Popov3.2K views
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co by Mail.ru Group
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
Mail.ru Group10K views
Dts x dicoding #2 memulai pemrograman kotlin by Ahmad Arif Faizin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlin
Ahmad Arif Faizin242 views
Letswift19-clean-architecture by Jung Kim
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architecture
Jung Kim1.6K views
Explaining ES6: JavaScript History and What is to Come by Cory Forsyth
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 Forsyth1.7K views

Viewers also liked

Faster Python by
Faster PythonFaster Python
Faster PythonAnoop Thomas Mathew
6.7K views18 slides
Reversing the dropbox client on windows by
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windowsextremecoders
28.4K views23 slides
Euro python2011 High Performance Python by
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance PythonIan Ozsvald
3K views48 slides
Odessapy2013 - Graph databases and Python by
Odessapy2013 - Graph databases and PythonOdessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonMax Klymyshyn
56.8K views40 slides
Beyond tf idf why, what & how by
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & howlucenerevolution
10K views59 slides
Python Performance 101 by
Python Performance 101Python Performance 101
Python Performance 101Ankur Gupta
3.2K views20 slides

Viewers also liked(20)

Reversing the dropbox client on windows by extremecoders
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
extremecoders28.4K views
Euro python2011 High Performance Python by Ian Ozsvald
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
Ian Ozsvald3K views
Odessapy2013 - Graph databases and Python by Max Klymyshyn
Odessapy2013 - Graph databases and PythonOdessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and Python
Max Klymyshyn56.8K views
Python Performance 101 by Ankur Gupta
Python Performance 101Python Performance 101
Python Performance 101
Ankur Gupta3.2K views
Inside the ANN: A visual and intuitive journey to understand how artificial n... by XavierArrufat
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...
XavierArrufat1.6K views
Kick start graph visualization projects by Linkurious
Kick start graph visualization projectsKick start graph visualization projects
Kick start graph visualization projects
Linkurious5.6K views
Introduction to Apache Accumulo by Aaron Cordova
Introduction to Apache AccumuloIntroduction to Apache Accumulo
Introduction to Apache Accumulo
Aaron Cordova8.3K views
Deploying and Managing Hadoop Clusters with AMBARI by DataWorks Summit
Deploying and Managing Hadoop Clusters with AMBARIDeploying and Managing Hadoop Clusters with AMBARI
Deploying and Managing Hadoop Clusters with AMBARI
DataWorks Summit29.9K views
Tues factors of production by Travis Klein
Tues factors of productionTues factors of production
Tues factors of production
Travis Klein1K views
Day 9 westward expansion, women religion by Travis Klein
Day 9 westward expansion, women religionDay 9 westward expansion, women religion
Day 9 westward expansion, women religion
Travis Klein536 views
Dsc by ianil
DscDsc
Dsc
ianil2.2K views
The art of_being_healthy by Chandan Dubey
The art of_being_healthyThe art of_being_healthy
The art of_being_healthy
Chandan Dubey163 views
Social media worthy sites for educators by MaryMorrisCMS
Social media worthy sites for educatorsSocial media worthy sites for educators
Social media worthy sites for educators
MaryMorrisCMS499 views

Similar to Python Coroutines, Present and Future

Job Queue in Golang by
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
22.3K views82 slides
Non Blocking I/O for Everyone with RxJava by
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
2K views71 slides
Async programming and python by
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
4.3K views42 slides
Un dsl pour ma base de données by
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de donnéesRomain Lecomte
257 views44 slides
Generics and Inference by
Generics and InferenceGenerics and Inference
Generics and InferenceRichard Fox
173 views34 slides
Concurrency in Golang by
Concurrency in GolangConcurrency in Golang
Concurrency in GolangOliver N
847 views40 slides

Similar to Python Coroutines, Present and Future(20)

Job Queue in Golang by Bo-Yi Wu
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
Bo-Yi Wu22.3K views
Non Blocking I/O for Everyone with RxJava by Frank Lyaruu
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
Frank Lyaruu2K views
Un dsl pour ma base de données by Romain Lecomte
Un dsl pour ma base de donnéesUn dsl pour ma base de données
Un dsl pour ma base de données
Romain Lecomte257 views
Generics and Inference by Richard Fox
Generics and InferenceGenerics and Inference
Generics and Inference
Richard Fox173 views
Concurrency in Golang by Oliver N
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
Oliver N847 views
Flask patterns by it-people
Flask patternsFlask patterns
Flask patterns
it-people7.3K views
Akka Futures and Akka Remoting by Knoldus Inc.
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
Knoldus Inc.2.1K views
Think Async: Asynchronous Patterns in NodeJS by Adam L Barrett
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett282 views
Advanced Python, Part 2 by Zaar Hai
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
Zaar Hai957 views
Introduction to Reactive Extensions without saying functional reactive by Tetsuharu OHZEKI
Introduction to Reactive Extensions without saying functional reactiveIntroduction to Reactive Extensions without saying functional reactive
Introduction to Reactive Extensions without saying functional reactive
Tetsuharu OHZEKI611 views
Asynchronous web apps with the Play Framework 2.0 by Oscar Renalias
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 Renalias8.2K views
Tasks: you gotta know how to run them by Filipe Ximenes
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
Filipe Ximenes221 views
Coroutines in Kotlin. UA Mobile 2017. by UA Mobile
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile145 views
Coroutines in Kotlin. In-depth review by Dmytro Zaitsev
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
Dmytro Zaitsev426 views
Pick up the low-hanging concurrency fruit by Vaclav Pech
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
Vaclav Pech870 views
Giorgio zoppi cpp11concurrency by Giorgio Zoppi
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
Giorgio Zoppi32 views
Architecture Patterns in Practice with Kotlin. UA Mobile 2017. by UA Mobile
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 Mobile153 views

More from emptysquare

Cat-Herd's Crook by
Cat-Herd's CrookCat-Herd's Crook
Cat-Herd's Crookemptysquare
835 views39 slides
MongoDB Drivers And High Availability: Deep Dive by
MongoDB Drivers And High Availability: Deep DiveMongoDB Drivers And High Availability: Deep Dive
MongoDB Drivers And High Availability: Deep Diveemptysquare
684 views32 slides
What Is Async, How Does It Work, And When Should I Use It? by
What Is Async, How Does It Work, And When Should I Use It?What Is Async, How Does It Work, And When Should I Use It?
What Is Async, How Does It Work, And When Should I Use It?emptysquare
1.9K views30 slides
Python Performance Profiling: The Guts And The Glory by
Python Performance Profiling: The Guts And The GloryPython Performance Profiling: The Guts And The Glory
Python Performance Profiling: The Guts And The Gloryemptysquare
3.4K views26 slides
Python Performance: Single-threaded, multi-threaded, and Gevent by
Python Performance: Single-threaded, multi-threaded, and GeventPython Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and Geventemptysquare
9.4K views26 slides
Python, async web frameworks, and MongoDB by
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBemptysquare
7.3K views23 slides

More from emptysquare(6)

Cat-Herd's Crook by emptysquare
Cat-Herd's CrookCat-Herd's Crook
Cat-Herd's Crook
emptysquare835 views
MongoDB Drivers And High Availability: Deep Dive by emptysquare
MongoDB Drivers And High Availability: Deep DiveMongoDB Drivers And High Availability: Deep Dive
MongoDB Drivers And High Availability: Deep Dive
emptysquare684 views
What Is Async, How Does It Work, And When Should I Use It? by emptysquare
What Is Async, How Does It Work, And When Should I Use It?What Is Async, How Does It Work, And When Should I Use It?
What Is Async, How Does It Work, And When Should I Use It?
emptysquare1.9K views
Python Performance Profiling: The Guts And The Glory by emptysquare
Python Performance Profiling: The Guts And The GloryPython Performance Profiling: The Guts And The Glory
Python Performance Profiling: The Guts And The Glory
emptysquare3.4K views
Python Performance: Single-threaded, multi-threaded, and Gevent by emptysquare
Python Performance: Single-threaded, multi-threaded, and GeventPython Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and Gevent
emptysquare9.4K views
Python, async web frameworks, and MongoDB by emptysquare
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
emptysquare7.3K views

Recently uploaded

Java Platform Approach 1.0 - Picnic Meetup by
Java Platform Approach 1.0 - Picnic MeetupJava Platform Approach 1.0 - Picnic Meetup
Java Platform Approach 1.0 - Picnic MeetupRick Ossendrijver
27 views39 slides
From chaos to control: Managing migrations and Microsoft 365 with ShareGate! by
From chaos to control: Managing migrations and Microsoft 365 with ShareGate!From chaos to control: Managing migrations and Microsoft 365 with ShareGate!
From chaos to control: Managing migrations and Microsoft 365 with ShareGate!sammart93
9 views39 slides
The Research Portal of Catalonia: Growing more (information) & more (services) by
The Research Portal of Catalonia: Growing more (information) & more (services)The Research Portal of Catalonia: Growing more (information) & more (services)
The Research Portal of Catalonia: Growing more (information) & more (services)CSUC - Consorci de Serveis Universitaris de Catalunya
79 views25 slides
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院IttrainingIttraining
41 views8 slides
Melek BEN MAHMOUD.pdf by
Melek BEN MAHMOUD.pdfMelek BEN MAHMOUD.pdf
Melek BEN MAHMOUD.pdfMelekBenMahmoud
14 views1 slide
Vertical User Stories by
Vertical User StoriesVertical User Stories
Vertical User StoriesMoisés Armani Ramírez
12 views16 slides

Recently uploaded(20)

From chaos to control: Managing migrations and Microsoft 365 with ShareGate! by sammart93
From chaos to control: Managing migrations and Microsoft 365 with ShareGate!From chaos to control: Managing migrations and Microsoft 365 with ShareGate!
From chaos to control: Managing migrations and Microsoft 365 with ShareGate!
sammart939 views
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by IttrainingIttraining
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
Unit 1_Lecture 2_Physical Design of IoT.pdf by StephenTec
Unit 1_Lecture 2_Physical Design of IoT.pdfUnit 1_Lecture 2_Physical Design of IoT.pdf
Unit 1_Lecture 2_Physical Design of IoT.pdf
StephenTec12 views
Piloting & Scaling Successfully With Microsoft Viva by Richard Harbridge
Piloting & Scaling Successfully With Microsoft VivaPiloting & Scaling Successfully With Microsoft Viva
Piloting & Scaling Successfully With Microsoft Viva
Case Study Copenhagen Energy and Business Central.pdf by Aitana
Case Study Copenhagen Energy and Business Central.pdfCase Study Copenhagen Energy and Business Central.pdf
Case Study Copenhagen Energy and Business Central.pdf
Aitana16 views
Transcript: The Details of Description Techniques tips and tangents on altern... by BookNet Canada
Transcript: The Details of Description Techniques tips and tangents on altern...Transcript: The Details of Description Techniques tips and tangents on altern...
Transcript: The Details of Description Techniques tips and tangents on altern...
BookNet Canada135 views
PharoJS - Zürich Smalltalk Group Meetup November 2023 by Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi126 views
Igniting Next Level Productivity with AI-Infused Data Integration Workflows by Safe Software
Igniting Next Level Productivity with AI-Infused Data Integration Workflows Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Safe Software257 views
Black and White Modern Science Presentation.pptx by maryamkhalid2916
Black and White Modern Science Presentation.pptxBlack and White Modern Science Presentation.pptx
Black and White Modern Science Presentation.pptx
maryamkhalid291616 views
Data-centric AI and the convergence of data and model engineering: opportunit... by Paolo Missier
Data-centric AI and the convergence of data and model engineering:opportunit...Data-centric AI and the convergence of data and model engineering:opportunit...
Data-centric AI and the convergence of data and model engineering: opportunit...
Paolo Missier39 views
SAP Automation Using Bar Code and FIORI.pdf by Virendra Rai, PMP
SAP Automation Using Bar Code and FIORI.pdfSAP Automation Using Bar Code and FIORI.pdf
SAP Automation Using Bar Code and FIORI.pdf
Business Analyst Series 2023 - Week 3 Session 5 by DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10237 views

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