Skip to content

Instantly share code, notes, and snippets.

@goodmami
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goodmami/db21bbfd53279a7429b8 to your computer and use it in GitHub Desktop.
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
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
@goodmami
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment