Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python corountine examples
def recv_count():
try:
while True:
n = (yield)
print "T-minus", n
except GeneratorExit:
print "Kaboom!"
def ex1():
r = recv_count()
r.next() # initialize iterator
for i in range(5,0,-1):
r.send(i)
r.close()
#####
def counter(x):
n = 0
while n <= x:
v = (yield n)
if v is not None:
n = v
else:
n += 1
def ex2():
gen = counter(25)
for i in gen:
print i
if i == 15: # jump directly to 18
gen.send(18)
#####
def gen():
for i in range(0, 10):
# yields i and receives v from send
v = (yield i)
print "from send", v
# need to yield because send is waiting for an answer
yield "hello"
def ex3():
g = gen()
for i in g:
print "from 1st yield", i
v = g.send(i**2)
print "from 2nd yield", v
def ex4():
g = gen()
i = g.next()
print i
v = g.send(i**2)
print v
#####
class StopPower(Exception):
pass
def powertable():
for i in (2,3):
j = 1
while True:
try:
yield j, j ** i
j += 1
except StopPower:
yield
print "stopped"
break
def ex5():
it = powertable()
for j, jpower in it:
print j, jpower
if jpower > 100:
it.throw(StopPower)
if __name__ == "__main__":
import sys
import __main__
getattr(__main__, "ex" + str(sys.argv[1]))()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.