SF patch #1171417: bug fix for islice() in docs

This commit is contained in:
Raymond Hettinger 2005-03-27 20:11:44 +00:00
parent 267b868f23
commit fdf3bd6630
2 changed files with 12 additions and 9 deletions

View File

@ -252,14 +252,12 @@ by functions or loops that truncate the stream.
\begin{verbatim}
def islice(iterable, *args):
s = slice(*args)
next, stop, step = s.start or 0, s.stop, s.step or 1
for cnt, element in enumerate(iterable):
if cnt < next:
continue
if stop is not None and cnt >= stop:
break
it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
nexti = it.next()
for i, element in enumerate(iterable):
if i == nexti:
yield element
next += step
nexti = it.next()
\end{verbatim}
If \var{start} is \code{None}, then iteration starts at zero.

View File

@ -265,6 +265,11 @@ class TestBasicOps(unittest.TestCase):
self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10))
self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
# Test number of items consumed SF #1171417
it = iter(range(10))
self.assertEqual(list(islice(it, 3)), range(3))
self.assertEqual(list(it), range(3, 10))
# Test invalid arguments
self.assertRaises(TypeError, islice, xrange(10))
self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4)