back to Index

coroutines

couroutine tests


In [1]:
# Cross-notebook include shim
with open("nbinclude.ipynb") as nbinclude_f: # don't rename nbinclude_f
    import IPython.nbformat.current
    get_ipython().run_cell(IPython.nbformat.current.read(nbinclude_f, 'json').worksheets[0].cells[0].input)

In [4]:
def grep(pattern):
    print "Looking for %s" % pattern
    while True:
        line = (yield)
        if pattern in line:
            print line,

In [5]:
g = grep("python")

In [6]:
g.next()


Looking for python

In [8]:
g.send("Yeah, but no, but yeah, but no")

In [9]:
g.send("A series of tubes")

In [10]:
g.send("python generators rock!")


python generators rock!

In [4]:
import sys

In [5]:
def counter():
    i = 0;
    while True:
        i+=1
        print i
        sys.stdout.flush()
        yield

In [6]:
c=counter()

In [7]:
c.next()


1

In [35]:
c2=counter()

In [36]:
c2=counter()

In [37]:
c2.next()


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-37-fd006920af81> in <module>()
----> 1 c2.next()

AttributeError: 'function' object has no attribute 'next'

In [3]:
import coroutine


---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-3-3abae2bdac03> in <module>()
----> 1 import coroutine

ImportError: No module named coroutine

In [1]:
@coroutine
def printer():
    tmp=(yield)
    print tmp

def sender(coru):
    coru.send("hello")
    print "I'm sender"


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-1cd0709322d3> in <module>()
----> 1 @coroutine
      2 def printer():
      3     tmp=(yield)
      4     print tmp
      5 

NameError: name 'coroutine' is not defined

In [8]:
import time

In [9]:
def countersleep():
    i = 0;
    while True:
        i+=1
        print i
        print 'leaving...'
        sys.stdout.flush()
        time.sleep(1)
        print 'out!'
        yield

In [17]:
cs=countersleep()

In [19]:
next(cs)


2
leaving...
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-19-2473a9b0b1c8> in <module>()
----> 1 next(cs)

<ipython-input-9-2ae3be59f070> in countersleep()
      6         print 'leaving...'
      7         sys.stdout.flush()
----> 8         time.sleep(1)
      9         print 'out!'
     10         yield

KeyboardInterrupt: 

In [20]:
next(cs)


---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-20-2473a9b0b1c8> in <module>()
----> 1 next(cs)

StopIteration: 

In [ ]: