Skip to content

Commit ebe42b0

Browse files
committed
Reduce groupby.__next__ calls in all_equal
1 parent 4f4217c commit ebe42b0

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

more_itertools/recipes.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ def all_equal(iterable, key=None):
222222
for first in iterator:
223223
for second in iterator:
224224
return False
225+
return True
225226
return True
226227

227228

tests/test_recipes.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22
from doctest import DocTestSuite
33
from fractions import Fraction
44
from functools import reduce
5-
from itertools import combinations, count, permutations
5+
from itertools import combinations, count, groupby, permutations
66
from operator import mul
77
from math import factorial
88
from sys import version_info
99
from unittest import TestCase, skipIf
10+
from unittest.mock import patch
1011

1112
import more_itertools as mi
1213

@@ -158,6 +159,22 @@ def test_key(self):
158159
self.assertTrue(mi.all_equal('4٤໔4৪', key=int))
159160
self.assertFalse(mi.all_equal('Abc', key=str.casefold))
160161

162+
@patch('more_itertools.recipes.groupby', autospec=True)
163+
def test_groupby_calls(self, mock_groupby):
164+
next_count = 0
165+
166+
class _groupby(groupby):
167+
def __next__(true_self):
168+
nonlocal next_count
169+
next_count += 1
170+
return super().__next__()
171+
172+
mock_groupby.side_effect = _groupby
173+
iterable = iter('aaaaa')
174+
self.assertTrue(mi.all_equal(iterable))
175+
self.assertEqual(list(iterable), [])
176+
self.assertEqual(next_count, 2)
177+
161178

162179
class QuantifyTests(TestCase):
163180
"""Tests for ``quantify()``"""

0 commit comments

Comments
 (0)