Last active
August 29, 2015 14:03
-
-
Save goodmami/db21bbfd53279a7429b8 to your computer and use it in GitHub Desktop.
Using the send() function of a Python generator to approximate lookahead and other uses
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 regenerator(gen): | |
for x in gen: | |
regen = (yield x) | |
while regen is not None: | |
yield None # send() also yields something, so don't pull from gen again | |
regen = (yield regen) | |
gen = (i for i in range(10)) | |
regen = regenerator(gen) | |
v = next(regen) # 0 | |
regen.send(v) # we've seen it, but we want to unsee it; send it back | |
next(regen) # still 0 | |
regen.send(-1) # you don't have to send back the same value | |
next(regen) # -1 | |
next(regen) # 1 (back to where we left off) | |
regen.send(None) # yields 2, because None is the same as when send() is not used | |
next(regen) # 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See here: http://code.activestate.com/recipes/528943/