Skip to content

Commit

Permalink
announce: simplified approach to _chunks()
Browse files Browse the repository at this point in the history
Co-authored-by: Exirel <florian.strzelecki@gmail.com>
  • Loading branch information
dgw and Exirel committed Jul 24, 2021
1 parent 5aa9f67 commit aeb4bb6
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions sopel/modules/announce.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
"""
from __future__ import absolute_import, division, print_function, unicode_literals

import itertools

from sopel import plugin


Expand All @@ -21,15 +23,15 @@ def _chunks(items, size):
:return: a :term:`generator` of chunks
:rtype: :term:`generator` of :class:`tuple`
"""
# Need to convert non-subscriptable types like `dict_keys` objects
try:
items[0]
except TypeError:
items = tuple(items)

# from https://stackoverflow.com/a/312464/5991 with modified names for readability
for delim in range(0, len(items), size):
yield tuple(items[delim:delim + size])
# This approach is safer than slicing with non-subscriptable types,
# for example `dict_keys` objects
iterator = iter(items)
# TODO: Simplify to assignment expression (`while cond := expr`)
# when dropping Python 3.7
chunk = tuple(itertools.islice(iterator, size))
while chunk:
yield chunk
chunk = tuple(itertools.islice(iterator, size))


@plugin.command('announce')
Expand Down

0 comments on commit aeb4bb6

Please sign in to comment.