Created
January 29, 2016 20:43
-
-
Save jsheedy/accee0bf1b2f42832a6b to your computer and use it in GitHub Desktop.
a context manager / iterator which remembers the final value
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
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