Skip to content

Commit

Permalink
Make sliced work with numpy arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
bbayles committed Jan 11, 2020
1 parent 3150ad2 commit d3665d6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion more_itertools/more.py
Expand Up @@ -1061,7 +1061,7 @@ def sliced(seq, n):
For non-sliceable iterables, see :func:`chunked`.
"""
return takewhile(bool, (seq[i : i + n] for i in count(0, n)))
return takewhile(len, (seq[i : i + n] for i in count(0, n)))


def split_at(iterable, pred):
Expand Down
20 changes: 20 additions & 0 deletions tests/test_more.py
Expand Up @@ -1076,6 +1076,26 @@ def test_not_sliceable(self):
with self.assertRaises(TypeError):
list(mi.sliced(seq, 3))

def test_numpy_like_array(self):
# Numpy arrays don't behave like Python lists - calling bool()
# on them doesn't return False for empty lists and True for non-empty
# ones. Emulate that behavior.
class FalseList(list):
def __getitem__(self, key):
ret = super().__getitem__(key)
if isinstance(key, slice):
return FalseList(ret)

return ret

def __bool__(self):
return False

seq = FalseList(range(9))
actual = list(mi.sliced(seq, 3))
expected = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
self.assertEqual(actual, expected)


class SplitAtTests(TestCase):
"""Tests for ``split()``"""
Expand Down

0 comments on commit d3665d6

Please sign in to comment.