I am creating a generator that is consumed by another function, but I still would like to know how many elements were generated:
lines = (line.rstrip('\n') for line in sys.stdin) process(lines) print("Processed {} lines.".format( ? ))
The best I can come up with is to wrap the generator in a class that holds the count, or maybe turn it inside out and send () things. Is there an elegant and efficient way to see how many elements a generator is if you are not the one who consumes it in Python 2?
Edit:. Here I have finished:
class Count(Iterable): """Wrap an iterable (typically a generator) and provide a ``count`` field counting the number of items. Accessing the ``count`` field before iteration is finished will invalidate the count. """ def __init__(self, iterable): self._iterable = iterable self._counter = itertools.count() def __iter__(self): return itertools.imap(operator.itemgetter(0), itertools.izip(self._iterable, self._counter)) @property def count(self): self._counter = itertools.repeat(self._counter.next()) return self._counter.next()
python generator count
Jay hacker
source share