Skip to content

Commit

Permalink
Add assert_ordered function
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Jan 5, 2019
1 parent 281fc35 commit c5868e0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

The ``duplicates`` function now takes an arbitrary number of iterables.

Added ``assert_ordered`` function.

4.1
===

Expand Down
20 changes: 20 additions & 0 deletions jaraco/itertools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1026,3 +1026,23 @@ def duplicates(*iterables, **kwargs):
def has_dupes(group):
return len(group) > 1
return filter(has_dupes, groups)


def assert_ordered(iterable, key=lambda x: x, comp=operator.le):
"""
Assert that for all items in the iterable, they're in order based on comp
>>> list(assert_ordered(range(5)))
[0, 1, 2, 3, 4]
>>> list(assert_ordered(range(5), comp=operator.gt))
Traceback (most recent call last):
...
AssertionError: not <built-in function gt> (0, 1)
>>> list(assert_ordered(range(5, 0, -1), key=operator.neg))
[5, 4, 3, 2, 1]
"""
for pair in more_itertools.pairwise(iterable):
keyed = tuple(map(key, pair))
assert comp(*keyed), "not {comp} {keyed}".format(**locals())
yield pair[0]
yield pair[1]

0 comments on commit c5868e0

Please sign in to comment.