Add a Counter class.

This commit is contained in:
Eric Snow 2018-03-01 22:37:43 +00:00
parent 87fffa7bdb
commit 04abc78a1c

60
tests/helpers/counter.py Normal file
View file

@ -0,0 +1,60 @@
class Counter(object):
"""An introspectable, dynamic alternative to itertools.count()."""
def __init__(self, start=0, step=1):
self._start = int(start)
self._step = int(step)
def __repr__(self):
if self._last is None:
start = self._start
else:
start = self._last + self._step
return '{}(start={}, step={})'.format(
type(self).__name__,
start,
self._step,
)
def __iter__(self):
return self
def __next__(self):
try:
self._last += self._step
except AttributeError:
self._last = self._start
return self._last
@property
def start(self):
return self._start
@property
def step(self):
return self._step
@property
def last(self):
try:
return self._last
except AttributeError:
return None
def peek(self, iterations=1):
"""Return the value that will be used next."""
try:
last = self._last
except AttributeError:
last = self._start - self._step
return last + self._step * iterations
def reset(self, start=None):
"""Set the next value to the given one.
If no value is provided then the previous start value is used.
"""
if start is not None:
self._start = int(start)
self._next = self._start