Skip to content

Commit 2284cec

Browse files
committed
Generators: return instead of raising StopIteration (vol. 1)
This commit fixes `window` and `butlastn`. See issue #39.
1 parent 2d46603 commit 2284cec

1 file changed

Lines changed: 12 additions & 3 deletions

File tree

unpythonic/it.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -397,10 +397,16 @@ def butlastn(n, iterable):
397397
it = iter(iterable)
398398
q = deque()
399399
for _ in range(n + 1):
400-
q.append(next(it))
400+
try:
401+
q.append(next(it))
402+
except StopIteration:
403+
return
401404
while True:
402405
yield q.popleft()
403-
q.append(next(it))
406+
try:
407+
q.append(next(it))
408+
except StopIteration:
409+
return
404410

405411
def first(iterable, *, default=None):
406412
"""Like nth, but return the first item."""
@@ -691,7 +697,10 @@ def windowed():
691697
while True:
692698
yield tuple(xs)
693699
xs.popleft()
694-
xs.append(next(it)) # let StopIteration propagate
700+
try:
701+
xs.append(next(it))
702+
except StopIteration:
703+
return
695704
return windowed()
696705

697706
def chunked(n, iterable):

0 commit comments

Comments
 (0)