Created
July 4, 2010 04:46
-
-
Save mblondel/463137 to your computer and use it in GitHub Desktop.
Python corountine examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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