-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
62 lines (48 loc) · 1.7 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
""" Polyfills for the `itertools` module.
Usage:
```pycon
>>> from polyfills import itertools
>>> itertools.batched("Hello World", 3)
['Hel', 'lo ', 'Wor', 'ld']
```
"""
import unittest as _unittest
try:
# If available, use `xrange` instead of `range`:
# - On Python 2, `xrange` returns an iterator, while `range` returns a list.
# - On Python 3, `xrange` does not exist, and `range` returns an iterator.
range = xrange # pyright: ignore[reportUndefinedVariable]
except NameError:
pass
def batched(iterable, length):
# type: (str|list|tuple, int) -> list[str]
""" Groups the specified string into chunks of the specified length.
New in Python 3.12.
Args:
iterable (str|list|tuple): The iterable to group.
length (int): The length of each chunk.
Returns:
chunks (list): A list of strings/tuples containing the chunks of the specified iterable.
Examples:
```pycon
>>> batched("Hello World", 3)
['Hel', 'lo ', 'Wor', 'ld']
```
"""
batched_data = [
iterable[i:i+length]
for i in range(0, len(iterable), length)
]
if type(iterable) in [type("")]:
return batched_data
return [tuple(_elem) for _elem in batched_data]
class BatchedTestCase(_unittest.TestCase):
def test_string(self):
self.assertEqual(batched("Hello World", 3), ['Hel', 'lo ', 'Wor', 'ld'])
def test_list(self):
flattened_data = ['roses', 'red', 'violets', 'blue', 'sugar', 'sweet']
unflattened = list(batched(flattened_data, 2))
self.assertEqual(
unflattened,
[('roses', 'red'), ('violets', 'blue'), ('sugar', 'sweet')],
)