The heapq library

The asyncstdlib.heapq library implements Python’s heapq for (async) functions and (async) iterables.

New in version 3.10.3.

This module does not re-implement the functions to maintain a heap data structure. Since Python’s heapq module does not support an internal key function but relies on (key, item) pairs as needed, the same interface can be used for async key function. For example, an async key function would be used as heappush(heap, (await key_func(item), item)) instead of heappush(heap, (key_func(item), item)).

Iterator merging

async for :T in merge(*iterables: (async) iter T, key: (T) (await) Any = None, reverse: bool = False)[source]

Merge all pre-sorted (async) iterables into a single sorted iterator

This works similar to sorted(chain(*iterables), key=key, reverse=reverse) but operates lazily: at any moment only one item of each iterable is stored for the comparison. This allows merging streams of pre-sorted items, such as timestamped records from multiple sources.

The optional key argument specifies a one-argument (async) callable, which provides a substitute for determining the sort order of each item. The special value and default None represents the identity function, comparing items directly.

The default sort order is ascending, that is items with a < b imply a is yielded before b. Use reverse=True for descending sort order. The iterables must be pre-sorted in the same order.

Iterator selecting

await nlargest(*iterables: (async) iter T, n: int, key: (T) (await) Any = None) [T, ...][source]

Return a sorted list of the n largest elements from the (async) iterable

The optional key argument specifies a one-argument (async) callable, which provides a substitute for determining the sort order of each item. The special value and default None represents the identity functions, comparing items directly.

The result is equivalent to sorted(iterable, key=key, reverse=True)[:n], but iterable is consumed lazily and items are discarded eagerly.

await nsmallest(*iterables: (async) iter T, n: int, key: (T) (await) Any = None) [T, ...][source]

Return a sorted list of the n smallest elements from the (async) iterable

Provides the reverse functionality to nlargest().