1 """Helpers for working with collections."""
3 from collections.abc
import Collection, Iterable
4 from functools
import partial
5 from itertools
import islice
9 def take(take_num: int, iterable: Iterable) -> list[Any]:
10 """Return first n items of the iterable as a list.
12 From itertools recipes
14 return list(islice(iterable, take_num))
17 def chunked(iterable: Iterable, chunked_num: int) -> Iterable[Any]:
18 """Break *iterable* into lists of length *n*.
22 return iter(partial(take, chunked_num, iter(iterable)), [])
25 def chunked_or_all(iterable: Collection[Any], chunked_num: int) -> Iterable[Any]:
26 """Break *collection* into iterables of length *n*.
28 Returns the collection if its length is less than *n*.
30 Unlike chunked, this function requires a collection so it can
31 determine the length of the collection and return the collection
32 if it is less than *n*.
34 if len(iterable) <= chunked_num:
36 return chunked(iterable, chunked_num)
list[Any] take(int take_num, Iterable iterable)
Iterable[Any] chunked(Iterable iterable, int chunked_num)
Iterable[Any] chunked_or_all(Collection[Any] iterable, int chunked_num)