I need a function to iterate through a python iterable in chunks. That is, it takes an iterable and a size of n and yields generators iterating through each chunk of size n. After some experimentation, I wrote this stupid hack because it seems there is no easy way to preemptively check whether an iterable has been exhausted. How can I improve this code?
def iterchunks(it, n):
def next_n(it_, n_, return_first = None):
if return_first is not None:
n_ -= 1
yield return_first
for _ in range(n_):
yield next(it_)
# check if the iterator is exhausted by advancing the iterator,
# if not return the value returned by advancing the iterator along with the boolean result
def exhausted(it_):
res = next(it_, None)
return res is None, res
while True:
exhsted, rf = exhausted(it)
if exhsted:
return
else:
# if the iterator is not exhausted, yield the returned value along with the next chunk
yield next_n(it, n, rf)