Skip to content

Raise LookupError in partition_all when length is invalid #603

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion toolz/itertoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -732,7 +732,12 @@ def partition_all(n, seq):
try:
# If seq defines __len__, then
# we can quickly calculate where no_pad starts
yield prev[:len(seq) % n]
end = len(seq) % n
if prev[end - 1] is no_pad or prev[end] is not no_pad:
raise LookupError(
'The sequence passed to `parition_all` has invalid length'
)
yield prev[:end]
except TypeError:
# Get first index of no_pad without using .index()
# https://github.com/pytoolz/toolz/issues/387
Expand Down
14 changes: 14 additions & 0 deletions toolz/tests/test_itertoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,20 @@ def __eq__(self, other):
assert list(partition_all(4, [obj]*7)) == result
assert list(partition_all(4, iter([obj]*7))) == result

# Test invalid __len__: https://github.com/pytoolz/toolz/issues/602
class ListWithBadLength(list):
def __init__(self, contents, off_by=1):
self.off_by = off_by
super().__init__(contents)

def __len__(self):
return super().__len__() + self.off_by

too_long_list = ListWithBadLength([1, 2], off_by=+1)
assert raises(LookupError, lambda: list(partition_all(5, too_long_list)))
too_short_list = ListWithBadLength([1, 2], off_by=-1)
assert raises(LookupError, lambda: list(partition_all(5, too_short_list)))


def test_count():
assert count((1, 2, 3)) == 3
Expand Down