-
-
Notifications
You must be signed in to change notification settings - Fork 405
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
announce: make _chunks()
helper safe against more input types
#2166
Conversation
Especially `dict_keys` objects, which is how py3 handles `dict.keys()` (vs. being a subscriptable iterable in py2). Added a test, too, because let's not have this plugin bite us again.
What about any of these 2 versions to get some chunk? Option 1: use import itertools
def chunk(items, size):
iterator = iter(items)
data = tuple(itertools.islice(iterator, size))
while data:
yield data
data = tuple(itertools.islice(iterator, size)) And this version uses a mutable list, but it might be easier to read when you don't know what def chunk(items, size):
acc = []
for i, item in enumerate(items, start=1):
acc.append(item)
if i % size == 0:
yield tuple(acc)
acc = []
if acc:
yield tuple(acc) |
I like the >>> while chunk := itertools.islice(iterator, 3):
... print(chunk)
...
<itertools.islice object at 0x7f3d2b211400>
<itertools.islice object at 0x7f3d2b0e19a0>
<itertools.islice object at 0x7f3d2b211400>
[many more repetitions]
<itertools.islice object at 0x7f3d2b0e19a0>
<itertools.islice object at 0x7f3d2b211400>
<itertools.islice object at 0x7f3d2b0e19a0>
^CTraceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
>>> while chunk := tuple(itertools.islice(iterator, 3)):
... print(chunk)
...
(1, 2, 3)
(4, 5, 6)
(7, 8) (Note that now I'm drunk on dropping old Python versions and wish it was reasonable to support only 3.8+ already because the |
Co-authored-by: Exirel <[email protected]>
Because |
announce: make `_chunks()` helper safe against more input types Cherry-picked from master: b38a5d6
Description
Fixes #2165.
Python 3
dict.keys()
returns adict_keys
object, which is not subscriptable unlike the return value in py2.Also made the generator return a consistent type (always tuple), and updated the documentation (not that it's actually used anywhere by Sphinx). Added a test, too, because let's (try to) not have this plugin bite us again.
Checklist
make qa
(runsmake quality
andmake test
)make quality
on both py3(.8) and py2(.7), and the patch should be clean against both. Since this can't be a straight cherry-pick back to7.1.x
due to the new test file needing different headers, I have pre-prepped anannounce-py2-backport
branch for myself with the appropriate code style.