Added utils.iter.limited, an iterable that limits the number of elements that can be taken from another iterable.

This commit is contained in:
Jeremy Fincher 2005-05-30 19:19:11 +00:00
parent c268aab9bd
commit b5f1e2a3e7
2 changed files with 19 additions and 0 deletions

View File

@ -158,4 +158,15 @@ def startswith(long, short):
except StopIteration:
return True
def limited(iterable, limit):
i = limit
iterable = iter(iterable)
try:
while i:
yield iterable.next()
i -= 1
except StopIteration:
raise ValueError, 'Expected %s elements in iterable (%r), got %s.' % \
(limit, iterable, limit-i)
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:

View File

@ -384,6 +384,14 @@ class StrTest(SupyTestCase):
class IterTest(SupyTestCase):
def testLimited(self):
L = range(10)
self.assertEqual([], list(utils.iter.limited(L, 0)))
self.assertEqual([0], list(utils.iter.limited(L, 1)))
self.assertEqual([0, 1], list(utils.iter.limited(L, 2)))
self.assertEqual(range(10), list(utils.iter.limited(L, 10)))
self.assertRaises(ValueError, list, utils.iter.limited(L, 11))
def testRandomChoice(self):
choice = utils.iter.choice
self.assertRaises(IndexError, choice, {})