objectif
Découper en blocs de taille fixe (fallback pour versions plus anciennes).
code minimal
import itertools
try:
b = list(itertools.batched(range(5), 2))
except AttributeError:
def batched(iterable, n):
it = iter(iterable)
while True:
chunk = tuple([next(it, None) for _ in range(n)])
chunk = tuple(x for x in chunk if x is not None)
if not chunk: break
yield chunk
b = list(batched(range(5), 2))
print(b == [(0,1),(2,3),(4,)]) # attendu: True
utilisation
import itertools
xs = list(getattr(itertools, "batched", lambda it, n: (tuple(it),))(range(3), 2))
print(len(xs) >= 1)
variante(s) utile(s)
import itertools
print(hasattr(itertools, "batched") or True)
notes
- itertools.batched existe en 3.12+; fournissez un fallback sinon.
- Utile pour paginer des appels réseau ou I/O.