fictive.patterns.iterables module

Common patterns for working with iterable objects

Functions

chunks

create an iterator that splits input_ into objects of length chunk_size

fictive.patterns.iterables.chunks(input_: Iterable, chunk_size: int)[source]

create an iterator that splits input_ into objects of length chunk_size

if input_ is a typing.Sequence, the generated chunks will be slices of input_. Otherwise, the generated chunks will themselves be independent generators on input_.

The last chunk will contain len(input_) % chunk_size elements

>>> from fictive.patterns.iterables import chunks
>>> sample = 'spam and eggs'
>>> chunks(sample, 5)
<generator object chunks at ...>
>>> for chunk in chunks(sample, 5):
...     print(chunk)
spam
and e
ggs
>>> sample = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
>>> chunk_generators = list(chunks(sample, 4))
>>> chunk_generators
[<itertools.islice object at ...>,          <itertools.islice object at ...>,          <itertools.islice object at ...>]
>>> list(chunk_generators[2])
[9, 10]
>>> list(chunk_generators[0])
[1, 2, 3, 4]