Skip to content

Instantly share code, notes, and snippets.

@fitzgen
Created November 7, 2010 22:15
Show Gist options
  • Save fitzgen/666919 to your computer and use it in GitHub Desktop.
Save fitzgen/666919 to your computer and use it in GitHub Desktop.
import pickle
# Simple generator that counts up to maximum, but you can set the counter by
# sending in new values.
def counter(maximum):
i = 0
while i < maximum:
val = (yield i)
# If value provided, change counter
if val is not None:
i = val
else:
i += 1
it = counter(10)
print "First:", it.next()
# First: 0
it.send(4)
print "After inserting 4:", it.next()
# After inserting 4: 5
# Serialize the generator.
f = open("_dumped", "w")
f.write(pickle.dumps(it))
f.close()
import pickle
# Deserialize the generator.
f = open("_dumped", "r")
it = pickle.loads(f.read())
f.close()
print "After serialization:"
for x in it:
print x
# After serialization:
# 6
# 7
# 8
# 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment