Created
July 8, 2013 21:59
-
-
Save gavinwahl/5952850 to your computer and use it in GitHub Desktop.
consume_once
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
from itertools import tee | |
class consume_once(object): | |
""" | |
Takes an iterator and returns an iterable that can be consumed | |
multiple times while only consuming the original a single time. | |
>>> x = consume_once(i for i in range(3)) | |
>>> list(x) | |
[0, 1, 2] | |
>>> list(x) | |
[0, 1, 2] | |
""" | |
def __init__(self, iterator): | |
self.iterator = iterator | |
def __iter__(self): | |
my_iterator, self.iterator = tee(self.iterator) | |
return my_iterator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please don't use this, a much better implementation is
consume_once = list