Skip to content

Instantly share code, notes, and snippets.

@erain
Created December 4, 2013 09:22
Show Gist options
  • Save erain/7784686 to your computer and use it in GitHub Desktop.
Save erain/7784686 to your computer and use it in GitHub Desktop.
An example of Coroutine in Python.
def read_producer(text, coroutines):
for word in text.split():
for coroutine in coroutines:
coroutine.send(word)
for coroutine in coroutines:
coroutine.close()
def match_filter(pattern, next_coroutine):
print("Looking for {0}".format(pattern))
try:
while True:
line = (yield)
if pattern in line:
next_coroutine.send(line)
except GeneratorExit:
print("Filter Done.")
next_coroutine.close()
def print_consumer():
print('Preparing to print')
try:
while True:
line = (yield)
print(line)
except GeneratorExit:
print("Consumer done.")
def main():
text = "Commending spending is offending to people pending lending!"
print("Original text: {0}".format(text))
printer = print_consumer()
printer.next()
m1 = match_filter("mend", printer)
m2 = match_filter("pe", printer)
m1.next()
m2.next()
read_producer(text, [m1, m2])
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment