The heapq library¶
The asyncstdlib.heapq
library implements
Python’s heapq
for (async) functions and (async) iterables.
Added 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 iteratorThis 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 defaultNone
represents the identity function, comparing items directly.The default sort order is ascending, that is items with
a < b
implya
is yielded beforeb
. Usereverse=True
for descending sort order. Theiterables
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) iterableThe 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 defaultNone
represents the identity functions, comparing items directly.The result is equivalent to
sorted(iterable, key=key, reverse=True)[:n]
, butiterable
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) iterableProvides the reverse functionality to
nlargest()
.