Skip to content

Instantly share code, notes, and snippets.

@thehale
Created September 5, 2023 18:15
Show Gist options
  • Save thehale/77734a52b1729efdf48a44165cdef3ee to your computer and use it in GitHub Desktop.
Save thehale/77734a52b1729efdf48a44165cdef3ee to your computer and use it in GitHub Desktop.
Python Batching Function with Generic Type Hints
from typing import Iterable, TypeVar
T = TypeVar("T")
def next_x(_i: Iterable[T], x: int) -> Iterable[Iterable[T]]:
gen = (i for i in _i)
batch = []
for item in gen:
batch.append(item)
if len(batch) == x:
yield batch
batch = []
yield batch # len(_i) % x items
@thehale
Copy link
Author

thehale commented Sep 5, 2023

LICENSE: MPL-2.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment