Skip to content

Commit 9b32076

Browse files
explicitly create batches, check batch size when done
1 parent 6117a1a commit 9b32076

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

asyncstdlib/itertools.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,11 +134,19 @@ async def batched(
134134
"""
135135
if n < 1:
136136
raise ValueError("n must be at least one")
137-
if strict:
138-
raise NotImplemented("batched(..., strict=True)")
139137
async with ScopedIter(iterable) as item_iter:
140-
while batch := await atuple(islice(_borrow(item_iter), n)):
141-
yield batch
138+
while True:
139+
batch: list[T] = []
140+
try:
141+
for _ in range(n):
142+
batch.append(await anext(item_iter))
143+
except StopAsyncIteration:
144+
if strict and len(batch) < n:
145+
raise ValueError("batched(): incomplete batch")
146+
if batch:
147+
yield tuple(batch)
148+
else:
149+
break
142150

143151

144152
class chain(AsyncIterator[T]):

0 commit comments

Comments
 (0)