Skip to content

Commit aeb4bb6

Browse files
dgwExirel
andcommitted
announce: simplified approach to _chunks()
Co-authored-by: Exirel <florian.strzelecki@gmail.com>
1 parent 5aa9f67 commit aeb4bb6

1 file changed

Lines changed: 11 additions & 9 deletions

File tree

sopel/modules/announce.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
"""
1010
from __future__ import absolute_import, division, print_function, unicode_literals
1111

12+
import itertools
13+
1214
from sopel import plugin
1315

1416

@@ -21,15 +23,15 @@ def _chunks(items, size):
2123
:return: a :term:`generator` of chunks
2224
:rtype: :term:`generator` of :class:`tuple`
2325
"""
24-
# Need to convert non-subscriptable types like `dict_keys` objects
25-
try:
26-
items[0]
27-
except TypeError:
28-
items = tuple(items)
29-
30-
# from https://stackoverflow.com/a/312464/5991 with modified names for readability
31-
for delim in range(0, len(items), size):
32-
yield tuple(items[delim:delim + size])
26+
# This approach is safer than slicing with non-subscriptable types,
27+
# for example `dict_keys` objects
28+
iterator = iter(items)
29+
# TODO: Simplify to assignment expression (`while cond := expr`)
30+
# when dropping Python 3.7
31+
chunk = tuple(itertools.islice(iterator, size))
32+
while chunk:
33+
yield chunk
34+
chunk = tuple(itertools.islice(iterator, size))
3335

3436

3537
@plugin.command('announce')

0 commit comments

Comments
 (0)