API Reference

builtins

Async-compatible versions of builtin functions for iterables.

These functions intentionally shadow their builtins counterparts, enabling use with both standard iterables and async iterables, without needing to use if/else clauses or awkward logic. Standard iterables get wrapped in async generators, and all functions are designed for use with await, async for, etc.

aioitertools.builtins.enumerate(itr: Union[Iterable[T], AsyncIterable[T]], start: int = 0) → AsyncIterator[Tuple[int, T]]

Consume a mixed iterable and yield the current index and item.

Example:

async for index, value in enumerate(…):

aioitertools.builtins.iter(itr: Union[Iterable[T], AsyncIterable[T]]) → AsyncIterator[T]

Get an async iterator from any mixed iterable.

Async iterators will be returned directly. Async iterables will return an async iterator. Standard iterables will be wrapped in an async generator yielding each item in the iterable in the same order.

Examples:

async for iter(range(10)):

async aioitertools.builtins.list(itr: Union[Iterable[T], AsyncIterable[T]]) → List[T]

Consume a mixed iterable and return a list of items in order.

Example:

await list(range(5)) -> [0, 1, 2, 3, 4]

aioitertools.builtins.map(fn: Callable[[T], R], itr: Union[Iterable[T], AsyncIterable[T]]) → AsyncIterator[R]

Modify item of a mixed iterable using the given function or coroutine.

Example:

async for response in map(func, data):

async aioitertools.builtins.max(itr: Union[Iterable[aioitertools.helpers.Orderable], AsyncIterable[aioitertools.helpers.Orderable]], *, key: Optional[Callable] = 'None') → aioitertools.helpers.Orderable
async aioitertools.builtins.max(itr: Union[Iterable[aioitertools.helpers.Orderable], AsyncIterable[aioitertools.helpers.Orderable]], *, default: T, key: Optional[Callable] = 'None') → Union[aioitertools.helpers.Orderable, T]

Return the largest item in an iterable or the largest of two or more arguments.

Example:

await min(range(5)) -> 4

async aioitertools.builtins.min(itr: Union[Iterable[aioitertools.helpers.Orderable], AsyncIterable[aioitertools.helpers.Orderable]], *, key: Optional[Callable] = 'None') → aioitertools.helpers.Orderable
async aioitertools.builtins.min(itr: Union[Iterable[aioitertools.helpers.Orderable], AsyncIterable[aioitertools.helpers.Orderable]], *, default: T, key: Optional[Callable] = 'None') → Union[aioitertools.helpers.Orderable, T]

Return the smallest item in an iterable or the smallest of two or more arguments.

Example:

await min(range(5)) -> 0

async aioitertools.builtins.next(itr: Union[Iterator[T], AsyncIterator[T]]) → T

Return the next item of any mixed iterator.

Calls builtins.next() on standard iterators, and awaits itr.__anext__() on async iterators.

Example:

value = await next(it)

async aioitertools.builtins.set(itr: Union[Iterable[T], AsyncIterable[T]]) → Set[T]

Consume a mixed iterable and return a set of items.

Example:

await set([0, 1, 2, 3, 0, 1, 2, 3]) -> {0, 1, 2, 3}

async aioitertools.builtins.sum(itr: Union[Iterable[T], AsyncIterable[T]], start: T = None) → T

Compute the sum of a mixed iterable, adding each value with the start value.

Example:

await sum(generator()) -> 1024

aioitertools.builtins.zip(__iter1: Union[Iterable[T1], AsyncIterable[T1]]) → AsyncIterator[Tuple[T1]]
aioitertools.builtins.zip(__iter1: Union[Iterable[T1], AsyncIterable[T1]], __iter2: Union[Iterable[T2], AsyncIterable[T2]]) → AsyncIterator[Tuple[T1, T2]]
aioitertools.builtins.zip(__iter1: Union[Iterable[T1], AsyncIterable[T1]], __iter2: Union[Iterable[T2], AsyncIterable[T2]], __iter3: Union[Iterable[T3], AsyncIterable[T3]]) → AsyncIterator[Tuple[T1, T2, T3]]
aioitertools.builtins.zip(__iter1: Union[Iterable[T1], AsyncIterable[T1]], __iter2: Union[Iterable[T2], AsyncIterable[T2]], __iter3: Union[Iterable[T3], AsyncIterable[T3]], __iter4: Union[Iterable[T4], AsyncIterable[T4]]) → AsyncIterator[Tuple[T1, T2, T3, T4]]
aioitertools.builtins.zip(__iter1: Union[Iterable[T1], AsyncIterable[T1]], __iter2: Union[Iterable[T2], AsyncIterable[T2]], __iter3: Union[Iterable[T3], AsyncIterable[T3]], __iter4: Union[Iterable[T4], AsyncIterable[T4]], __iter5: Union[Iterable[T5], AsyncIterable[T5]]) → AsyncIterator[Tuple[T1, T2, T3, T4, T5]]
aioitertools.builtins.zip(__iter1: Union[Iterable[Any], AsyncIterable[Any]], __iter2: Union[Iterable[Any], AsyncIterable[Any]], __iter3: Union[Iterable[Any], AsyncIterable[Any]], __iter4: Union[Iterable[Any], AsyncIterable[Any]], __iter5: Union[Iterable[Any], AsyncIterable[Any]], __iter6: Union[Iterable[Any], AsyncIterable[Any]], *__iterables: Union[Iterable[Any], AsyncIterable[Any]]) → AsyncIterator[Tuple[Any, ]]

Yield a tuple of items from mixed iterables until the shortest is consumed.

Example:

async for a, b, c in zip(i, j, k):

itertools

Async-compatible version of itertools standard library functions.

These functions build on top of the async builtins components, enabling use of both standard iterables and async iterables, without needing to use if/else clauses or awkward logic. Standard iterables get wrapped in async generators, and all functions are designed for use with await, async for, etc.

See https://docs.python.org/3/library/itertools.html for reference.

aioitertools.itertools.accumulate(itr: Union[Iterable[T], AsyncIterable[T]], func: Union[Callable[[T, T], T], Callable[[T, T], Awaitable[T]]] = <built-in function add>) → AsyncIterator[T]

Yield the running accumulation of an iterable and operator.

Accepts both a standard function or a coroutine for accumulation.

Example:

data = [1, 2, 3, 4]

async def mul(a, b):

return a * b

async for total in accumulate(data, func=mul):

… # 1, 2, 6, 24

aioitertools.itertools.combinations(itr: Union[Iterable[T], AsyncIterable[T]], r: int) → AsyncIterator[Tuple[T, ]]

Yield r length subsequences from the given iterable.

Simple wrapper around itertools.combinations for asyncio. This will consume the entire iterable before yielding values.

Example:

async for value in combinations(range(4), 3):

… # (0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)

aioitertools.itertools.combinations_with_replacement(itr: Union[Iterable[T], AsyncIterable[T]], r: int) → AsyncIterator[Tuple[T, ]]

Yield r length subsequences from the given iterable with replacement.

Simple wrapper around itertools.combinations_with_replacement. This will consume the entire iterable before yielding values.

Example:

async for value in combinations_with_replacement(“ABC”, 2):

… # (“A”, “A”), (“A”, “B”), (“A”, “C”), (“B”, “B”), …

aioitertools.itertools.compress(itr: Union[Iterable[T], AsyncIterable[T]], selectors: Union[Iterable[Any], AsyncIterable[Any]]) → AsyncIterator[T]

Yield elements only when the corresponding selector evaluates to True.

Stops when either the iterable or the selectors have been exhausted.

Example:

async for value in compress(range(5), [1, 0, 0, 1, 1]):

… # 0, 3, 4

aioitertools.itertools.count(start: N = 0, step: N = 1) → AsyncIterator[N]

Yield an infinite series, starting at the given value and increasing by step.

Example:

async for value in counter(10, -1):

… # 10, 9, 8, 7, …

aioitertools.itertools.cycle(itr: Union[Iterable[T], AsyncIterable[T]]) → AsyncIterator[T]

Yield a repeating series from the given iterable.

Lazily consumes the iterable when the next value is needed, and caching the values in memory for future iterations of the series.

Example:

async for value in cycle([1, 2]):

… # 1, 2, 1, 2, 1, 2, …

aioitertools.itertools.dropwhile(predicate: Union[Callable[[T], object], Callable[[T], Awaitable[object]]], iterable: Union[Iterable[T], AsyncIterable[T]]) → AsyncIterator[T]

Drops all items until the predicate evaluates False; yields all items afterwards.

Accepts both standard functions and coroutines for the predicate.

Example:

def pred(x):

return x < 4

async for item in dropwhile(pred, range(6)):

… # 4, 5, 6

aioitertools.itertools.filterfalse(predicate: Union[Callable[[T], object], Callable[[T], Awaitable[object]]], iterable: Union[Iterable[T], AsyncIterable[T]]) → AsyncIterator[T]

Yield items from the iterable only when the predicate evaluates to False.

Accepts both standard functions and coroutines for the predicate.

Example:

def pred(x):

return x < 4

async for item in filterfalse(pred, range(6)):

… # 4, 5

aioitertools.itertools.groupby(itr: Union[Iterable[T], AsyncIterable[T]]) → AsyncIterator[Tuple[T, List[T]]]
aioitertools.itertools.groupby(itr: Union[Iterable[T], AsyncIterable[T]], key: Union[Callable[[T], R], Callable[[T], Awaitable[R]]]) → AsyncIterator[Tuple[R, List[T]]]

Yield consecutive keys and groupings from the given iterable.

Items will be grouped based on the key function, which defaults to the identity of each item. Accepts both standard functions and coroutines for the key function. Suggest sorting by the key function before using groupby.

Example:

data = [“A”, “a”, “b”, “c”, “C”, “c”]

async for key, group in groupby(data, key=str.lower):

key # “a”, “b”, “c” group # [“A”, “a”], [“b”], [“c”, “C”, “c”]

aioitertools.itertools.islice(itr: Union[Iterable[T], AsyncIterable[T]], __stop: Optional[int]) → AsyncIterator[T]
aioitertools.itertools.islice(itr: Union[Iterable[T], AsyncIterable[T]], __start: int, __stop: Optional[int], __step: int = '1') → AsyncIterator[T]

Yield selected items from the given iterable.

islice(iterable, stop) islice(iterable, start, stop[, step])

Starting from the start index (or zero), stopping at the stop index (or until exhausted), skipping items if step > 0.

Example:

data = range(10)

async for item in islice(data, 5):

… # 0, 1, 2, 3, 4

async for item in islice(data, 2, 5):

… # 2, 3, 4

async for item in islice(data, 1, 7, 2):

… # 1, 3, 5

aioitertools.itertools.permutations(itr: Union[Iterable[T], AsyncIterable[T]], r: Optional[int] = None) → AsyncIterator[Tuple[T, ]]

Yield r length permutations of elements in the iterable.

Simple wrapper around itertools.combinations for asyncio. This will consume the entire iterable before yielding values.

Example:

async for value in permutations(range(3)):

… # (0, 1, 2), (0, 2, 1), (1, 0, 2), …

aioitertools.itertools.product(*itrs: Union[Iterable[T], AsyncIterable[T]], repeat: int = 1) → AsyncIterator[Tuple[T, ]]

Yield cartesian products of all iterables.

Simple wrapper around itertools.combinations for asyncio. This will consume all iterables before yielding any values.

Example:

async for value in product(“abc”, “xy”):

… # (“a”, “x”), (“a”, “y”), (“b”, “x”), …

async for value in product(range(3), repeat=3):

… # (0, 0, 0), (0, 0, 1), (0, 0, 2), …

aioitertools.itertools.repeat(elem: T, n: int = - 1) → AsyncIterator[T]

Yield the given value repeatedly, forever or up to n times.

Example:

async for value in repeat(7):

… # 7, 7, 7, 7, 7, 7, …

aioitertools.itertools.starmap(fn: Union[Callable[[], R], Callable[[], Awaitable[R]]], iterable: Union[Iterable[Union[Iterable[Any], AsyncIterable[Any]]], AsyncIterable[Union[Iterable[Any], AsyncIterable[Any]]]]) → AsyncIterator[R]

Yield values from a function using an iterable of iterables for arguments.

Each iterable contained within will be unpacked and consumed before executing the function or coroutine.

Example:

data = [(1, 1), (1, 1, 1), (2, 2)]

async for value in starmap(operator.add, data):

… # 2, 3, 4

aioitertools.itertools.takewhile(predicate: Union[Callable[[T], object], Callable[[T], Awaitable[object]]], iterable: Union[Iterable[T], AsyncIterable[T]]) → AsyncIterator[T]

Yield values from the iterable until the predicate evaluates False.

Accepts both standard functions and coroutines for the predicate.

Example:

def pred(x):

return x < 4

async for value in takewhile(pred, range(8)):

… # 0, 1, 2, 3

aioitertools.itertools.tee(itr: Union[Iterable[T], AsyncIterable[T]], n: int = 2) → Tuple[AsyncIterator[T], ]

Return n iterators that each yield items from the given iterable.

The first iterator lazily fetches from the original iterable, and then queues the values for the other iterators to yield when needed.

Caveat: all iterators are dependent on the first iterator – if it is consumed more slowly than the rest, the other consumers will be blocked until the first iterator continues forward. Similarly, if the first iterator is consumed more quickly than the rest, more memory will be used in keeping values in the queues until the other iterators finish consuming them.

Example:

it1, it2 = tee(range(5), n=2)

async for value in it1:

… # 0, 1, 2, 3, 4

async for value in it2:

… # 0, 1, 2, 3, 4

aioitertools.itertools.zip_longest(*itrs: Union[Iterable[Any], AsyncIterable[Any]], fillvalue: Any = None) → AsyncIterator[Tuple[Any, ]]

Yield a tuple of items from mixed iterables until all are consumed.

If shorter iterables are exhausted, the default value will be used until all iterables are exhausted.

Example:

a = range(3) b = range(5)

async for a, b in zip_longest(a, b, fillvalue=-1):

a # 0, 1, 2, -1, -1 b # 0, 1, 2, 3, 4

more_itertools

aioitertools.more_itertools.chunked(iterable: Union[Iterable[T], AsyncIterable[T]], n: int) → AsyncIterable[List[T]]

Break iterable into chunks of length n.

The last chunk will be shorter if the total number of items is not divisible by n.

Example:

async for chunk in chunked([1, 2, 3, 4, 5], n=2):

… # first iteration: chunk == [1, 2]; last one: chunk == [5]

async aioitertools.more_itertools.take(n: int, iterable: Union[Iterable[T], AsyncIterable[T]]) → List[T]

Return the first n items of iterable as a list.

If there are too few items in iterable, all of them are returned. n needs to be at least 0. If it is 0, an empty list is returned.

Example:

first_two = await take(2, [1, 2, 3, 4, 5])

asyncio

Friendlier version of asyncio standard library.

Provisional library. Must be imported as aioitertools.asyncio.

aioitertools.asyncio.as_completed(aws: Iterable[Awaitable[T]], *, loop: Optional[asyncio.events.AbstractEventLoop] = None, timeout: Optional[float] = None) → AsyncIterator[T]

Run awaitables in aws concurrently, and yield results as they complete.

Unlike asyncio.as_completed, this yields actual results, and does not require awaiting each item in the iterable.

Example:

async for value in as_completed(futures):

… # use value immediately

async aioitertools.asyncio.gather(*args: Awaitable[T], loop: Optional[asyncio.events.AbstractEventLoop] = None, return_exceptions: bool = False, limit: int = - 1) → List[Any]

Like asyncio.gather but with a limit on concurrency.

Much of the complexity of gather comes with it support for cancel, which we omit here. Note that all results are buffered.