Created
February 18, 2015 08:22
-
-
Save lmatt-bit/218ba1733f6beae369c5 to your computer and use it in GitHub Desktop.
Use yield to implement coroutine
This file contains hidden or 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 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