Skip to content

Commit 701712f

Browse files
committed
Handle StopIteration in Python 3.7+
Add more tests for edge cases
1 parent 4ea6619 commit 701712f

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

toolz/itertoolz.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -375,8 +375,11 @@ def second(seq):
375375
'B'
376376
"""
377377
seq = iter(seq)
378-
next(seq)
379-
return next(seq)
378+
try:
379+
next(seq)
380+
return next(seq)
381+
except StopIteration:
382+
raise
380383

381384

382385
def nth(n, seq):

toolz/tests/test_itertoolz.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
from toolz.compatibility import range, filter
1818
from operator import add, mul
1919

20+
import pytest
21+
2022

2123
# is comparison will fail between this and no_default
2224
no_default2 = loads(dumps('__no__default__'))
@@ -143,6 +145,12 @@ def test_second():
143145
assert second('ABCDE') == 'B'
144146
assert second((3, 2, 1)) == 2
145147
assert isinstance(second({0: 'zero', 1: 'one'}), int)
148+
assert second(x for x in range(2)) == 1
149+
150+
# Python 3.7, StopIteration should be raised if iterable too short
151+
with pytest.raises(StopIteration):
152+
second([])
153+
second([0])
146154

147155

148156
def test_last():

0 commit comments

Comments
 (0)