Home Assistant Unofficial Reference 2024.12.1
collection.py
Go to the documentation of this file.
1 """Helpers for working with collections."""
2 
3 from collections.abc import Collection, Iterable
4 from functools import partial
5 from itertools import islice
6 from typing import Any
7 
8 
9 def take(take_num: int, iterable: Iterable) -> list[Any]:
10  """Return first n items of the iterable as a list.
11 
12  From itertools recipes
13  """
14  return list(islice(iterable, take_num))
15 
16 
17 def chunked(iterable: Iterable, chunked_num: int) -> Iterable[Any]:
18  """Break *iterable* into lists of length *n*.
19 
20  From more-itertools
21  """
22  return iter(partial(take, chunked_num, iter(iterable)), [])
23 
24 
25 def chunked_or_all(iterable: Collection[Any], chunked_num: int) -> Iterable[Any]:
26  """Break *collection* into iterables of length *n*.
27 
28  Returns the collection if its length is less than *n*.
29 
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*.
33  """
34  if len(iterable) <= chunked_num:
35  return (iterable,)
36  return chunked(iterable, chunked_num)
list[Any] take(int take_num, Iterable iterable)
Definition: collection.py:9
Iterable[Any] chunked(Iterable iterable, int chunked_num)
Definition: collection.py:17
Iterable[Any] chunked_or_all(Collection[Any] iterable, int chunked_num)
Definition: collection.py:25