Skip to content

Instantly share code, notes, and snippets.

@gavinwahl
Created July 8, 2013 21:59
Show Gist options
  • Save gavinwahl/5952850 to your computer and use it in GitHub Desktop.
Save gavinwahl/5952850 to your computer and use it in GitHub Desktop.
consume_once
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
@gavinwahl
Copy link
Author

Please don't use this, a much better implementation is consume_once = list

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