Skip to content

Instantly share code, notes, and snippets.

@Veedrac
Created September 24, 2013 11:40
Show Gist options
  • Save Veedrac/6683519 to your computer and use it in GitHub Desktop.
Save Veedrac/6683519 to your computer and use it in GitHub Desktop.
class IterCount(object):
def __init__(self, iterable):
self._iterable = iterable
self._count = 0
def _itercount(self):
for value in self._iterable:
self._count += 1
yield value
def __iter__(self):
return self._itercount()
@property
def count(self):
return self._count
class CountItemsWrapper:
def __init__(self, items):
self.items = iter(items)
self.count = 0
def __next__(self):
res = next(self.items)
self.count += 1
return res
def __iter__(self):
return self
# Heh, it's a pun! Like, 'cause I'm "countering" your argument ;)
countering = CountItemsWrapper([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
for x, y in zip(countering, range(5)):
pass
for item in countering:
pass
countering.count
#>>> 10
for item in countering:
pass
countering.count
#>>> 10
# And again...
countering = IterCount([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
for x, y in zip(countering, range(5)):
pass
for item in countering:
pass
countering.count
#>>> 16
for item in countering:
pass
countering.count
#>>> 26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment