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 (Union[Iterable[Union[Any, Awaitable[Any]]], AsyncIterable[Union[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 (Union[Iterable[Union[Any, Awaitable[Any]]], AsyncIterable[Union[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 (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

Return type

AsyncIterator[aioitertools.types.T]

async aioitertools.builtins.next(itr: Union[Iterator[aioitertools.types.T], AsyncIterator[aioitertools.types.T]]) aioitertools.types.T
async aioitertools.builtins.next(itr: Union[Iterator[aioitertools.types.T1], AsyncIterator[aioitertools.types.T1]], default: aioitertools.types.T2) Union[aioitertools.types.T1, aioitertools.types.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 (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

Return type

List[aioitertools.types.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 (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

Return type

Set[aioitertools.types.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
  • itr (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

  • start (int) –

Return type

AsyncIterator[Tuple[int, aioitertools.types.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
  • fn (Callable[[aioitertools.types.T], aioitertools.types.R]) –

  • itr (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

Return type

AsyncIterator[aioitertools.types.R]

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: aioitertools.types.T, key: Optional[Callable] = 'None') Union[aioitertools.helpers.Orderable, aioitertools.types.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: 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: aioitertools.types.T, key: Optional[Callable] = 'None') Union[aioitertools.helpers.Orderable, aioitertools.types.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
  • itr (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

  • start (Optional[aioitertools.types.T]) –

Return type

aioitertools.types.T

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

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
  • itr (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

  • func (Union[Callable[[aioitertools.types.T, aioitertools.types.T], aioitertools.types.T], Callable[[aioitertools.types.T, aioitertools.types.T], Awaitable[aioitertools.types.T]]]) –

Return type

AsyncIterator[aioitertools.types.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
  • itr (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

  • r (int) –

Return type

AsyncIterator[Tuple[aioitertools.types.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
  • itr (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

  • r (int) –

Return type

AsyncIterator[Tuple[aioitertools.types.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
  • itr (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

  • selectors (Union[Iterable[Any], AsyncIterable[Any]]) –

Return type

AsyncIterator[aioitertools.types.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 (aioitertools.types.N) –

  • step (aioitertools.types.N) –

Return type

AsyncIterator[aioitertools.types.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 (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

Return type

AsyncIterator[aioitertools.types.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
  • predicate (Union[Callable[[aioitertools.types.T], object], Callable[[aioitertools.types.T], Awaitable[object]]]) –

  • iterable (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

Return type

AsyncIterator[aioitertools.types.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
  • predicate (Union[Callable[[aioitertools.types.T], object], Callable[[aioitertools.types.T], Awaitable[object]]]) –

  • iterable (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

Return type

AsyncIterator[aioitertools.types.T]

async aioitertools.itertools.groupby(itr: Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) AsyncIterator[Tuple[aioitertools.types.T, List[aioitertools.types.T]]]
async aioitertools.itertools.groupby(itr: Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]], key: Union[Callable[[aioitertools.types.T], aioitertools.types.R], Callable[[aioitertools.types.T], Awaitable[aioitertools.types.R]]]) AsyncIterator[Tuple[aioitertools.types.R, List[aioitertools.types.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: Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]], __stop: Optional[int]) AsyncIterator[aioitertools.types.T]
async aioitertools.itertools.islice(itr: Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]], __start: int, __stop: Optional[int], __step: int = 1) AsyncIterator[aioitertools.types.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
  • itr (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

  • r (Optional[int]) –

Return type

AsyncIterator[Tuple[aioitertools.types.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
  • itrs (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

  • repeat (int) –

Return type

AsyncIterator[Tuple[aioitertools.types.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 (aioitertools.types.T) –

  • n (int) –

Return type

AsyncIterator[aioitertools.types.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
  • fn (Union[Callable[[...], aioitertools.types.R], Callable[[...], Awaitable[aioitertools.types.R]]]) –

  • iterable (Union[Iterable[Union[Iterable[Any], AsyncIterable[Any]]], AsyncIterable[Union[Iterable[Any], AsyncIterable[Any]]]]) –

Return type

AsyncIterator[aioitertools.types.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
  • predicate (Union[Callable[[aioitertools.types.T], object], Callable[[aioitertools.types.T], Awaitable[object]]]) –

  • iterable (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

Return type

AsyncIterator[aioitertools.types.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
  • itr (Union[Iterable[aioitertools.types.T], AsyncIterable[aioitertools.types.T]]) –

  • n (int) –

Return type

Tuple[AsyncIterator[aioitertools.types.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
  • itrs (Union[Iterable[Any], AsyncIterable[Any]]) –

  • fillvalue (Optional[Any]) –

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
  • n (int) –

  • iterable (Union[Iterable[aioitertools.more_itertools.T], AsyncIterable[aioitertools.more_itertools.T]]) –

Return type

List[aioitertools.more_itertools.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
  • iterable (Union[Iterable[aioitertools.more_itertools.T], AsyncIterable[aioitertools.more_itertools.T]]) –

  • n (int) –

Return type

AsyncIterable[List[aioitertools.more_itertools.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
  • predicate (Union[Callable[[aioitertools.more_itertools.T], object], Callable[[aioitertools.more_itertools.T], Awaitable[object]]]) –

  • iterable (Union[Iterable[aioitertools.more_itertools.T], AsyncIterable[aioitertools.more_itertools.T]]) –

Return type

Tuple[AsyncIterable[aioitertools.more_itertools.T], AsyncIterable[aioitertools.more_itertools.T]]

asyncio

Friendlier version of asyncio standard library.

Provisional library. Must be imported as aioitertools.asyncio.

aioitertools.asyncio.as_completed(aws, *, loop=None, 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
  • aws (Iterable[Awaitable[aioitertools.types.T]]) –

  • loop (Optional[asyncio.events.AbstractEventLoop]) –

  • timeout (Optional[float]) –

Return type

AsyncIterator[aioitertools.types.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
  • iterables (Iterable[AsyncIterable[aioitertools.types.T]]) –

  • return_exceptions (bool) –

Return type

AsyncIterable[aioitertools.types.T]

aioitertools.asyncio.gather(*args, loop=None, 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
  • args (Awaitable[aioitertools.types.T]) –

  • loop (Optional[asyncio.events.AbstractEventLoop]) –

  • return_exceptions (bool) –

  • limit (int) –

Return type

List[Any]

aioitertools.asyncio.gather_iter(itr, loop=None, 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
  • itr (Union[Iterable[Union[aioitertools.types.T, Awaitable[aioitertools.types.T]]], AsyncIterable[Union[aioitertools.types.T, Awaitable[aioitertools.types.T]]]]) –

  • loop (Optional[asyncio.events.AbstractEventLoop]) –

  • return_exceptions (bool) –

  • limit (int) –

Return type

List[aioitertools.types.T]