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.

async aioitertools.builtins.all(itr)

Return True if all values are truthy in a mixed iterable, else False. The iterable will be fully consumed and any awaitables will automatically be awaited.

Example:

if await all(it):
    ...
Parameters:

itr (Iterable[Any | Awaitable[Any]] | AsyncIterable[Any | Awaitable[Any]]) –

Return type:

bool

async aioitertools.builtins.any(itr)

Return True if any value is truthy in a mixed iterable, else False. The iterable will be fully consumed and any awaitables will automatically be awaited.

Example:

if await any(it):
    ...
Parameters:

itr (Iterable[Any | Awaitable[Any]] | AsyncIterable[Any | Awaitable[Any]]) –

Return type:

bool

aioitertools.builtins.iter(itr)

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 value in iter(range(10)):
    ...
Parameters:

itr (Iterable[T] | AsyncIterable[T]) –

Return type:

AsyncIterator[T]

async aioitertools.builtins.next(itr: Iterator[T] | AsyncIterator[T]) T
async aioitertools.builtins.next(itr: Iterator[T1] | AsyncIterator[T1], default: T2) T1 | T2

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.list(itr)

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

Example:

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

itr (Iterable[T] | AsyncIterable[T]) –

Return type:

List[T]

async aioitertools.builtins.tuple(itr)

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

Example:

await tuple(range(5))
-> (0, 1, 2, 3, 4)
Parameters:

itr (Iterable[T] | AsyncIterable[T]) –

Return type:

Tuple[T, …]

async aioitertools.builtins.set(itr)

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}
Parameters:

itr (Iterable[T] | AsyncIterable[T]) –

Return type:

Set[T]

async aioitertools.builtins.enumerate(itr, start=0)

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

Example:

async for index, value in enumerate(...):
    ...
Parameters:
Return type:

AsyncIterator[Tuple[int, T]]

async aioitertools.builtins.map(fn, itr)

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

Example:

async for response in map(func, data):
    ...
Parameters:
Return type:

AsyncIterator[R]

async aioitertools.builtins.max(itr: Iterable[Orderable] | AsyncIterable[Orderable], *, key: Callable | None = None) Orderable
async aioitertools.builtins.max(itr: Iterable[Orderable] | AsyncIterable[Orderable], *, default: T, key: Callable | None = None) Orderable | T

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

Example:

await max(range(5))
-> 4
async aioitertools.builtins.min(itr: Iterable[Orderable] | AsyncIterable[Orderable], *, key: Callable | None = None) Orderable
async aioitertools.builtins.min(itr: Iterable[Orderable] | AsyncIterable[Orderable], *, default: T, key: Callable | None = None) 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.sum(itr, start=None)

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

Example:

await sum(generator())
-> 1024
Parameters:
Return type:

T

async aioitertools.builtins.zip(__iter1: Iterable[T1] | AsyncIterable[T1]) AsyncIterator[Tuple[T1]]
async aioitertools.builtins.zip(__iter1: Iterable[T1] | AsyncIterable[T1], __iter2: Iterable[T2] | AsyncIterable[T2]) AsyncIterator[Tuple[T1, T2]]
async aioitertools.builtins.zip(__iter1: Iterable[T1] | AsyncIterable[T1], __iter2: Iterable[T2] | AsyncIterable[T2], __iter3: Iterable[T3] | AsyncIterable[T3]) AsyncIterator[Tuple[T1, T2, T3]]
async aioitertools.builtins.zip(__iter1: Iterable[T1] | AsyncIterable[T1], __iter2: Iterable[T2] | AsyncIterable[T2], __iter3: Iterable[T3] | AsyncIterable[T3], __iter4: Iterable[T4] | AsyncIterable[T4]) AsyncIterator[Tuple[T1, T2, T3, T4]]
async aioitertools.builtins.zip(__iter1: Iterable[T1] | AsyncIterable[T1], __iter2: Iterable[T2] | AsyncIterable[T2], __iter3: Iterable[T3] | AsyncIterable[T3], __iter4: Iterable[T4] | AsyncIterable[T4], __iter5: Iterable[T5] | AsyncIterable[T5]) AsyncIterator[Tuple[T1, T2, T3, T4, T5]]
async aioitertools.builtins.zip(__iter1: Iterable[Any] | AsyncIterable[Any], __iter2: Iterable[Any] | AsyncIterable[Any], __iter3: Iterable[Any] | AsyncIterable[Any], __iter4: Iterable[Any] | AsyncIterable[Any], __iter5: Iterable[Any] | AsyncIterable[Any], __iter6: Iterable[Any] | AsyncIterable[Any], *__iterables: 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.

async aioitertools.itertools.accumulate(itr, func=<built-in function add>)

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
Parameters:
Return type:

AsyncIterator[T]

async aioitertools.itertools.combinations(itr, r)

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)
Parameters:
Return type:

AsyncIterator[Tuple[T, …]]

async aioitertools.itertools.combinations_with_replacement(itr, r)

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"), ...
Parameters:
Return type:

AsyncIterator[Tuple[T, …]]

async aioitertools.itertools.compress(itr, selectors)

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
Parameters:
Return type:

AsyncIterator[T]

async aioitertools.itertools.count(start=0, step=1)

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, ...
Parameters:
  • start (N) –

  • step (N) –

Return type:

AsyncIterator[N]

async aioitertools.itertools.cycle(itr)

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, ...
Parameters:

itr (Iterable[T] | AsyncIterable[T]) –

Return type:

AsyncIterator[T]

async aioitertools.itertools.dropwhile(predicate, iterable)

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
Parameters:
Return type:

AsyncIterator[T]

async aioitertools.itertools.filterfalse(predicate, iterable)

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
Parameters:
Return type:

AsyncIterator[T]

async aioitertools.itertools.groupby(itr: Iterable[T] | AsyncIterable[T]) AsyncIterator[Tuple[T, List[T]]]
async aioitertools.itertools.groupby(itr: Iterable[T] | AsyncIterable[T], key: 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"]
async aioitertools.itertools.islice(itr: Iterable[T] | AsyncIterable[T], __stop: int | None) AsyncIterator[T]
async aioitertools.itertools.islice(itr: Iterable[T] | AsyncIterable[T], __start: int, __stop: int | None, __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
async aioitertools.itertools.permutations(itr, r=None)

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), ...
Parameters:
Return type:

AsyncIterator[Tuple[T, …]]

async aioitertools.itertools.product(*itrs, repeat=1)

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), ...
Parameters:
Return type:

AsyncIterator[Tuple[T, …]]

async aioitertools.itertools.repeat(elem, n=-1)

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

Example:

async for value in repeat(7):
    ...  # 7, 7, 7, 7, 7, 7, ...
Parameters:
  • elem (T) –

  • n (int) –

Return type:

AsyncIterator[T]

async aioitertools.itertools.starmap(fn, iterable)

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
Parameters:
Return type:

AsyncIterator[R]

async aioitertools.itertools.takewhile(predicate, iterable)

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
Parameters:
Return type:

AsyncIterator[T]

aioitertools.itertools.tee(itr, n=2)

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
Parameters:
Return type:

Tuple[AsyncIterator[T], …]

async aioitertools.itertools.zip_longest(*itrs, fillvalue=None)

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
Parameters:
Return type:

AsyncIterator[Tuple[Any, …]]

more_itertools

async aioitertools.more_itertools.take(n, iterable)

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])
Parameters:
Return type:

List[T]

async aioitertools.more_itertools.chunked(iterable, n)

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]
Parameters:
Return type:

AsyncIterable[List[T]]

async aioitertools.more_itertools.before_and_after(predicate, iterable)

A variant of aioitertools.takewhile() that allows complete access to the remainder of the iterator.

>>> it = iter('ABCdEfGhI')
>>> all_upper, remainder = await before_and_after(str.isupper, it)
>>> ''.join([char async for char in all_upper])
'ABC'
>>> ''.join([char async for char in remainder])
'dEfGhI'

Note that the first iterator must be fully consumed before the second iterator can generate valid results.

Parameters:
Return type:

Tuple[AsyncIterable[T], AsyncIterable[T]]

asyncio

Friendlier version of asyncio standard library.

Provisional library. Must be imported as aioitertools.asyncio.

async aioitertools.asyncio.as_completed(aws, *, timeout=None)

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.

Cancels all remaining awaitables if a timeout is given and the timeout threshold is reached.

Example:

async for value in as_completed(futures):
    ...  # use value immediately
Parameters:
Return type:

AsyncIterator[T]

async aioitertools.asyncio.as_generated(iterables, *, return_exceptions=False)

Yield results from one or more async iterables, in the order they are produced.

Like as_completed(), but for async iterators or generators instead of futures. Creates a separate task to drain each iterable, and a single queue for results.

If return_exceptions is False, then any exception will be raised, and pending iterables and tasks will be cancelled, and async generators will be closed. If return_exceptions is True, any exceptions will be yielded as results, and execution will continue until all iterables have been fully consumed.

Example:

async def generator(x):
    for i in range(x):
        yield i

gen1 = generator(10)
gen2 = generator(12)

async for value in as_generated([gen1, gen2]):
    ...  # intermixed values yielded from gen1 and gen2
Parameters:
Return type:

AsyncIterable[T]

async aioitertools.asyncio.gather(*args, return_exceptions=False, limit=-1)

Like asyncio.gather but with a limit on concurrency.

Note that all results are buffered.

If gather is cancelled all tasks that were internally created and still pending will be cancelled as well.

Example:

futures = [some_coro(i) for i in range(10)]

results = await gather(*futures, limit=2)
Parameters:
Return type:

List[Any]

async aioitertools.asyncio.gather_iter(itr, return_exceptions=False, limit=-1)

Wrapper around gather to handle gathering an iterable instead of *args.

Note that the iterable values don’t have to be awaitable.

Parameters:
Return type:

List[T]