[Edu-sig] old macdonald had a farm (coroutines for noobs like me)
kirby urner
kirby.urner at gmail.com
Mon Apr 27 04:11:01 CEST 2009
"""
On the Farm: (Python 3 -- 3to2 easy)
for David Beazley, the gratitude, who wanted
something more useful than Fibonacci numbers
See:
http://oubiwann.blogspot.com/2009/04/generators-and-coroutines.html
(my comments appended)
"""
def coroutine(target):
"""
used to decorate generators we plan to
use as coroutines
"""
def initialize(*args, **kwargs):
thegen = target(*args, **kwargs)
next(thegen)
return thegen
return initialize
@coroutine
def screening(target, farmanimals):
var = ""
while True:
var = (yield)
print("I am a %s" % var)
if var in farmanimals:
target.send(var)
@coroutine
def process():
while True:
var = (yield)
print("Farm animal %s is being processed." % var)
def test():
"""
>>>
I am a cow
Farm animal cow is being processed.
I am a jackalope
I am a pig
Farm animal pig is being processed.
I am a monkey
"""
onthefarm = ["cow","pig","chicken"]
p2 = process()
p1 = screening(p2, onthefarm)
p1.send("cow")
p1.send("jackalope")
p1.send("pig")
p1.send("monkey")
if __name__ == "__main__":
test()
More information about the Edu-sig
mailing list