Skip to content

Commit 61de603

Browse files
committed
Add fast path in distinct()
1 parent 68efee8 commit 61de603

File tree

2 files changed

+9
-0
lines changed

2 files changed

+9
-0
lines changed

babel/util.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ def distinct(iterable: Iterable[_T]) -> Generator[_T, None, None]:
3838
3939
:param iterable: the iterable collection providing the data
4040
"""
41+
if isinstance(iterable, (tuple, list)) and len(iterable) <= 1:
42+
yield from iterable
43+
return
4144
seen = set()
4245
for item in iter(iterable):
4346
if item not in seen:

tests/test_util.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ class _FF:
3131
def test_distinct():
3232
assert list(util.distinct([1, 2, 1, 3, 4, 4])) == [1, 2, 3, 4]
3333
assert list(util.distinct('foobar')) == ['f', 'o', 'b', 'a', 'r']
34+
assert list(util.distinct(c for c in 'foobar')) == ['f', 'o', 'b', 'a', 'r']
35+
# Fast path exercises
36+
assert list(util.distinct([])) == []
37+
assert list(util.distinct(())) == []
38+
assert list(util.distinct(('a',))) == ['a']
39+
assert list(util.distinct(['a'])) == ['a']
3440

3541

3642
def test_pathmatch():

0 commit comments

Comments
 (0)