I wanted to learn about Iterable
and Iterators
and hence thought about getting my hands dirty rather than reading theory and forgetting it.
I am curious how I can improve readability and error handling of my code. I also thought to practice and include test cases.
class foo_range(object):
""" Custom range iterator which mimics native xrange. """
def __init__(self, start, stop, step=1):
try:
self.current = int(start)
self.limit = int(stop)
self.step = int(step)
except ValueError:
raise
if step == 0:
raise ValueError("Step can't be 0")
def __iter__(self):
return self
def next(self):
if self.step > 0 and self.current >= self.limit:
raise StopIteration()
if self.step < 0 and self.current <= self.limit:
raise StopIteration()
oldvalue = self.current
self.current += self.step
return oldvalue
import unittest
class TestXRange(unittest.TestCase):
def test_invalid_range(self):
with self.assertRaises(ValueError) as ve:
foo_range(0, 5, 0)
def test_valid_range(self):
expected = [0, 1, 2]
actual = []
for _ in foo_range(0, 3):
actual.append(_)
self.assertEqual(actual, expected)
expected = [0, -1, -2, -3]
actual = []
for _ in foo_range(0, -4, -1):
actual.append(_)
self.assertEqual(actual, expected)
expected = []
actual = []
for _ in foo_range(0, 5, -1):
actual.append(_)
self.assertEqual(actual, expected)
expected = []
actual = []
for _ in foo_range(0, -5, 1):
actual.append(_)
self.assertEqual(actual, expected)
if __name__ == '__main__':
unittest.main()