Skip to content

Instantly share code, notes, and snippets.

@lmatt-bit
Created February 18, 2015 08:22
Show Gist options
  • Select an option

  • Save lmatt-bit/218ba1733f6beae369c5 to your computer and use it in GitHub Desktop.

Select an option

Save lmatt-bit/218ba1733f6beae369c5 to your computer and use it in GitHub Desktop.
Use yield to implement coroutine
def coroutine(func):
def start(*args, **kwargs):
cr = func(*args, **kwargs)
cr.next()
return cr
return start
@coroutine
def grep(pattern):
print "looking for %s" % pattern
while True:
line = (yield)
if pattern in line:
print line
g = grep("python")
g.send("yeah, but no")
g.send("python test")
g.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment