Skip to content

Instantly share code, notes, and snippets.

@jsheedy
Created January 29, 2016 20:43
Show Gist options
  • Save jsheedy/accee0bf1b2f42832a6b to your computer and use it in GitHub Desktop.
Save jsheedy/accee0bf1b2f42832a6b to your computer and use it in GitHub Desktop.
a context manager / iterator which remembers the final value
import random
class Foo():
data = (random.randint(0, 1000) for x in range(10))
last = None
def __iter__(self):
return self
def __next__(self):
self.last = next(self.data)
return self.last
def __enter__(self):
return self
def __exit__(self, _e, _v, _t):
pass
with Foo() as f:
for x in f:
print(x)
print("final value {}".format(f.last))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment