From 6c2296283bf5e2a6f6badf4a30f8d9fe014a7ab0 Mon Sep 17 00:00:00 2001 From: Mahmoud Hashemi Date: Sun, 8 Feb 2015 14:09:56 -0800 Subject: [PATCH] defined/implemented windowed_iter corner case behavior --- boltons/iterutils.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/boltons/iterutils.py b/boltons/iterutils.py index 189071d..ec89662 100644 --- a/boltons/iterutils.py +++ b/boltons/iterutils.py @@ -172,19 +172,25 @@ def chunked_iter(src, size, **kw): def windowed_iter(src, size): """\ - Returns up to `size` tuples which represent a sliding window over - iterable `src`. - - TODO: behavior when len(src) < size + Returns tuples with length `size` which represent a sliding + window over iterable `src`. >>> list(windowed_iter(range(7), 3)) [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)] + + If the iterable is too short to make a window of length `size`, + then no window tuples are returned. + + >>> list(windowed_iter(range(3), 5)) + [] """ tees = itertools.tee(src, size) - for i, t in enumerate(tees): - for _ in xrange(i): - next(t) - + try: + for i, t in enumerate(tees): + for _ in xrange(i): + next(t) + except StopIteration: + return itertools.izip([]) return itertools.izip(*tees)