### Install aioitertools Source: https://github.com/omnilib/aioitertools/blob/main/docs/index.md Installs the aioitertools library using pip. Requires Python 3.9 or newer. ```shell pip install aioitertools ``` -------------------------------- ### Enumerate Iterable with aioitertools.enumerate Source: https://context7.com/omnilib/aioitertools/llms.txt Illustrates using `aioitertools.enumerate` to yield index and item pairs from a mixed iterable. It supports a custom start index for enumeration. ```python import asyncio from aioitertools import enumerate async def main(): async for index, value in enumerate(['a', 'b', 'c']): print(f"{index}: {value}") # 0: a # 1: b # 2: c # With custom start index async for index, value in enumerate(['x', 'y'], start=10): print(f"{index}: {value}") # 10: x # 11: y asyncio.run(main()) ``` -------------------------------- ### Get Next Item with aioitertools.next Source: https://context7.com/omnilib/aioitertools/llms.txt Shows how to retrieve the next item from a standard or async iterator using `aioitertools.next`. It also illustrates how to provide a default value to handle exhausted iterators gracefully. ```python import asyncio from aioitertools import iter, next async def main(): it = iter([1, 2, 3]) first = await next(it) print(first) # 1 second = await next(it) print(second) # 2 # With default value for exhausted iterator empty_it = iter([]) value = await next(empty_it, "default") print(value) # "default" asyncio.run(main()) ``` -------------------------------- ### Get first n items with take Source: https://context7.com/omnilib/aioitertools/llms.txt The `take` function from `aioitertools.more_itertools` returns the first `n` items from an iterable as a list. If the iterable contains fewer than `n` items, it returns all available items. It requires `asyncio` and `aioitertools.more_itertools`. ```python import asyncio from aioitertools.more_itertools import take async def main(): result = await take(3, range(10)) print(result) # [0, 1, 2] # If iterable has fewer items, return all of them result = await take(10, [1, 2, 3]) print(result) # [1, 2, 3] asyncio.run(main()) ``` -------------------------------- ### Generate infinite series with count (Python) Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Yields an infinite series of numbers starting from a specified value and incrementing by a step. This function is useful for generating sequences that continue indefinitely. The start and step parameters can be any number. ```python import aioitertools async def example(): async for value in aioitertools.itertools.count(10, -1): print(value) # Output: 10, 9, 8, ... ``` -------------------------------- ### count - Async infinite counter (Python) Source: https://context7.com/omnilib/aioitertools/llms.txt Yields an infinite series of numbers starting at a specified value and incrementing by a specified step. This is useful for generating sequences of numbers asynchronously. It can be limited using `islice`. ```python import asyncio from aioitertools import count, islice, list async def main(): # Count from 0 result = await list(islice(count(), 5)) print(result) # [0, 1, 2, 3, 4] # Count from 10 by 2 result = await list(islice(count(10, 2), 5)) print(result) # [10, 12, 14, 16, 18] # Count backwards result = await list(islice(count(100, -10), 5)) print(result) # [100, 90, 80, 70, 60] asyncio.run(main()) ``` -------------------------------- ### Calculate Sum Asynchronously with aioitertools.builtins.sum Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md The `aioitertools.builtins.sum` function computes the sum of elements in an asynchronous iterable, optionally starting with a given value. It iterates through the provided iterable and accumulates the sum. The `start` parameter defaults to 0 if not provided. ```python import asyncio import aioitertools async def generator(): for i in range(10): yield i async def main(): result = await aioitertools.builtins.sum(generator()) print(f"The sum is: {result}") asyncio.run(main()) ``` -------------------------------- ### Compute Sum of Iterable with aioitertools Source: https://context7.com/omnilib/aioitertools/llms.txt Calculates the sum of elements in an asynchronous iterable, with an optional starting value. It handles mixed iterables and awaits any awaitables within them. ```python import asyncio from aioitertools import sum async def main(): result = await sum(range(10)) print(result) # 45 # With start value result = await sum([1, 2, 3], start=100) print(result) # 106 asyncio.run(main()) ``` -------------------------------- ### aioitertools.builtins.sum Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Computes the sum of a mixed iterable, adding each value with the start value. Supports both synchronous and asynchronous iterables. ```APIDOC ## async aioitertools.builtins.sum ### Description Compute the sum of a mixed iterable, adding each value with the start value. ### Method ASYNC FUNCTION ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python await sum(generator()) ``` ### Response #### Success Response (200) - **Return type:** T - The computed sum of the iterable elements. #### Response Example ```json 1024 ``` ``` -------------------------------- ### Slice an Iterable with aioitertools.islice Source: https://context7.com/omnilib/aioitertools/llms.txt Yields a specified slice of elements from an asynchronous iterable, using start, stop, and step parameters. Useful for processing parts of large iterables. ```python import asyncio from aioitertools import islice, list async def main(): data = range(10) # First 5 items result = await list(islice(data, 5)) print(result) # [0, 1, 2, 3, 4] # Items 2-5 result = await list(islice(range(10), 2, 6)) print(result) # [2, 3, 4, 5] # Every other item from index 1 to 8 result = await list(islice(range(10), 1, 8, 2)) print(result) # [1, 3, 5, 7] asyncio.run(main()) ``` -------------------------------- ### Enumerate Iterable (Python) Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Consumes a mixed iterable (synchronous or asynchronous) and yields pairs of (index, item). The index can be optionally started from a specified value. This is commonly used when the index of each element is needed during iteration. ```python import aioitertools async def example(): async for index, value in aioitertools.builtins.enumerate(range(5)): print(f"Index: {index}, Value: {value}") # Expected output: # Index: 0, Value: 0 # Index: 1, Value: 1 # Index: 2, Value: 2 # Index: 3, Value: 3 # Index: 4, Value: 4 ``` -------------------------------- ### Get the next item from an async iterator Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md The `aioitertools.builtins.next` function retrieves the subsequent item from a mixed iterator (standard or asynchronous). For standard iterators, it calls the built-in `next()`; for async iterators, it awaits `_anext_()`. It supports an optional default value. ```python import aioitertools async def get_next_item(iterator): try: value = await aioitertools.builtins.next(iterator) print(f"Next item: {value}") except StopAsyncIteration: print("Iterator exhausted") async def get_next_with_default(iterator, default_value): value = await aioitertools.builtins.next(iterator, default_value) print(f"Next item or default: {value}") ``` -------------------------------- ### Async Islice with aioitertools Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Yields selected items from an async iterable. It supports slicing with a stop index, or start, stop, and step indices. This function is useful for taking a subset of items from a potentially large or infinite async iterable without loading all items into memory. ```python import asyncio from aioitertools.itertools import islice async def main(): data = range(10) print("islice(data, 5):") async for item in islice(data, 5): print(item, end=" ") # 0 1 2 3 4 print() print("islice(data, 2, 5):") async for item in islice(data, 2, 5): print(item, end=" ") # 2 3 4 print() print("islice(data, 1, 7, 2):") async for item in islice(data, 1, 7, 2): print(item, end=" ") # 1 3 5 print() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Basic Usage of aioitertools Source: https://github.com/omnilib/aioitertools/blob/main/docs/index.md Demonstrates basic usage of aioitertools, including iterating over async iterables and using map and zip with async functions. It shadows standard library functions for familiarity. ```python from aioitertools import iter, next, map, zip something = iter(...) first_item = await next(something) async for item in iter(something): ... async def fetch(url): response = await aiohttp.request(...) return response.json async for value in map(fetch, MANY_URLS): ... async for a, b in zip(something, something_else): ... ``` -------------------------------- ### Create Async Iterator with aioitertools.iter Source: https://context7.com/omnilib/aioitertools/llms.txt Demonstrates how to create an async iterator from both standard Python iterables (like range) and async generators using the `aioitertools.iter` function. This function ensures compatibility with async for loops. ```python import asyncio from aioitertools import iter async def main(): # Works with standard iterables async for value in iter(range(5)): print(value) # 0, 1, 2, 3, 4 # Works with async generators async def async_gen(): for i in range(3): yield i * 10 async for value in iter(async_gen()): print(value) # 0, 10, 20 asyncio.run(main()) ``` -------------------------------- ### aioitertools.asyncio.as_completed Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Runs awaitables concurrently and yields their results as they complete. This is a friendlier version of asyncio.as_completed. ```APIDOC ## async aioitertools.asyncio.as_completed(aws, timeout=None) ### Description Runs awaitables in `aws` concurrently, and yields results as they complete. Unlike `asyncio.as_completed`, this yields actual results directly, without requiring an additional await. ### Method GET ### Endpoint /omnilib/aioitertools/asyncio/as_completed ### Parameters #### Path Parameters None #### Query Parameters - **aws** (Iterable[Awaitable[T]]) - Required - An iterable of awaitables to run concurrently. - **timeout** (float | None) - Optional - A timeout in seconds. If reached, all remaining awaitables are cancelled. #### Request Body None ### Request Example ```python # Example usage (conceptual) async def my_coro(x): await asyncio.sleep(x) return x futures = [my_coro(3), my_coro(1), my_coro(2)] async for result in as_completed(futures): print(result) # Results will be printed in order 1, 2, 3 ``` ### Response #### Success Response (200) - **result** (T) - The result of a completed awaitable. #### Response Example ```json { "result": 1 } ``` ``` -------------------------------- ### Zip Iterables with aioitertools.zip Source: https://context7.com/omnilib/aioitertools/llms.txt Demonstrates combining multiple iterables element-wise using `aioitertools.zip`. It yields tuples of items until the shortest iterable is exhausted. ```python import asyncio from aioitertools import zip async def main(): names = ['Alice', 'Bob', 'Charlie'] ages = [25, 30, 35] cities = ['NYC', 'LA', 'Chicago'] async for name, age, city in zip(names, ages, cities): print(f"{name} is {age} from {city}") # Alice is 25 from NYC # Bob is 30 from LA # Charlie is 35 from Chicago asyncio.run(main()) ``` -------------------------------- ### starmap - Async map with unpacked arguments (Python) Source: https://context7.com/omnilib/aioitertools/llms.txt Applies a function to each iterable of arguments, unpacking the arguments from tuples or lists. This is useful when your function expects multiple arguments and your data is structured as iterables of argument groups. It works asynchronously. ```python import asyncio import operator from aioitertools import starmap, list async def main(): data = [(2, 3), (4, 5), (6, 7)] result = await list(starmap(operator.mul, data)) print(result) # [6, 20, 42] # With custom function def power(base, exp): return base ** exp result = await list(starmap(power, [(2, 3), (3, 2), (10, 2)])) print(result) # [8, 9, 100] asyncio.run(main()) ``` -------------------------------- ### combinations / permutations - Async combinatorics (Python) Source: https://context7.com/omnilib/aioitertools/llms.txt Generates all r-length combinations or permutations of elements from an asynchronous iterable. Combinations consider elements where order does not matter, while permutations consider order. These are useful for generating all possible arrangements or selections. ```python import asyncio from aioitertools import combinations, permutations, list async def main(): # Combinations (order doesn't matter) result = await list(combinations([1, 2, 3, 4], 2)) print(result) # [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] # Permutations (order matters) result = await list(permutations([1, 2, 3], 2)) print(result) # [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)] asyncio.run(main()) ``` -------------------------------- ### Consume Iterable to List with aioitertools.list Source: https://context7.com/omnilib/aioitertools/llms.txt Demonstrates consuming any iterable, including async generators, into a Python list using `aioitertools.list`. This function collects all items in order. ```python import asyncio from aioitertools import list, iter async def main(): # From standard iterable result = await list(range(5)) print(result) # [0, 1, 2, 3, 4] # From async generator async def async_gen(): for i in range(3): yield i * 2 result = await list(async_gen()) print(result) # [0, 2, 4] asyncio.run(main()) ``` -------------------------------- ### Get an async iterator from a mixed iterable Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md The `aioitertools.builtins.iter` function provides an asynchronous iterator from various iterable types, including standard iterables, async iterables, and async iterators. For standard iterables, it wraps them in an async generator. ```python import aioitertools async def process_iterable(mixed_iterable): async for value in aioitertools.builtins.iter(mixed_iterable): print(value) ``` -------------------------------- ### Async Itertools Functions Source: https://github.com/omnilib/aioitertools/blob/main/docs/index.md Shows how to use asynchronous versions of itertools functions like chain and islice from aioitertools. These functions work with both standard and async iterables. ```python from aioitertools import chain, islice async def generator1(...): yield ... async def generator2(...): yield ... async for value in chain(generator1(), generator2()): ... async for value in islice(generator1(), 2, None, 2): ... ``` -------------------------------- ### Consume Iterable to Tuple with aioitertools.tuple Source: https://context7.com/omnilib/aioitertools/llms.txt Shows how to consume any iterable, including async generators, into a Python tuple using `aioitertools.tuple`. This function collects all items in order. ```python import asyncio from aioitertools import tuple async def main(): result = await tuple(range(5)) print(result) # (0, 1, 2, 3, 4) asyncio.run(main()) ``` -------------------------------- ### aioitertools.more_itertools.before_and_after Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md A variant of takewhile that splits an asynchronous iterable into two parts based on a predicate. The first part contains elements before the predicate is met, and the second part contains the rest. ```APIDOC ## async aioitertools.more_itertools.before_and_after(predicate, iterable) ### Description A variant of `aioitertools.takewhile()` that allows complete access to the remainder of the iterator. It splits an async iterable into two async iterables: one yielding items before the predicate is met, and another yielding the remaining items. ### Method GET ### Endpoint /omnilib/aioitertools/more_itertools/before_and_after ### Parameters #### Path Parameters - **predicate** (Callable[[T], object] | Callable[[T], Awaitable[object]]) - Required - The predicate function to test items. - **iterable** (AsyncIterable[T]) - Required - The asynchronous iterable to process. #### Query Parameters None #### Request Body None ### Request Example ```python # Example usage (conceptual) it = iter('ABCdEfGhI') all_upper, remainder = await before_and_after(str.isupper, it) async for char in all_upper: print(char) # Prints A, B, C async for char in remainder: print(char) # Prints d, E, f, G, h, I ``` ### Response #### Success Response (200) - **tuple** (AsyncIterable[T], AsyncIterable[T]) - A tuple containing two asynchronous iterables: the first yielding items before the predicate is met, and the second yielding the remaining items. #### Response Example ```json { "before": ["A", "B", "C"], "after": ["d", "E", "f", "G", "h", "I"] } ``` ``` -------------------------------- ### Run awaitables concurrently with aioitertools.asyncio.as_completed Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Executes a collection of awaitables concurrently and yields their results as they complete. This is a friendlier version of asyncio.as_completed, yielding actual results directly without requiring an extra await. It supports an optional timeout that cancels remaining awaitables if reached. ```python3 async for value in as_completed(futures): ... # use value immediately ``` -------------------------------- ### combinations_with_replacement - Async combinations allowing repeats (Python) Source: https://context7.com/omnilib/aioitertools/llms.txt Generates r-length combinations with replacement from an asynchronous iterable. This means elements can be chosen multiple times. It's useful for scenarios where repetition is allowed in selections. ```python import asyncio from aioitertools import combinations_with_replacement, list async def main(): result = await list(combinations_with_replacement('AB', 2)) print(result) # [('A', 'A'), ('A', 'B'), ('B', 'B')] asyncio.run(main()) ``` -------------------------------- ### Async Combinations with Replacement Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Yields r-length subsequences from the given iterable, allowing for replacement. This is a wrapper around itertools.combinations_with_replacement for asyncio and consumes the entire iterable before yielding results. ```python import aioitertools async for value in aioitertools.itertools.combinations_with_replacement("ABC", 2): print(value) # Output: ('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C') ``` -------------------------------- ### Split Iterable with before_and_after (Python) Source: https://context7.com/omnilib/aioitertools/llms.txt Splits an async iterable into two iterables based on a predicate function. The first iterable yields items until the predicate returns False, and the second yields the remaining items. Requires `asyncio` and `aioitertools.more_itertools`. ```Python import asyncio from aioitertools.more_itertools import before_and_after async def main(): data = [1, 2, 3, 10, 4, 5] before, after = await before_and_after(lambda x: x < 5, data) # Must consume 'before' first before_list = [x async for x in before] after_list = [x async for x in after] print(before_list) print(after_list) asyncio.run(main()) ``` -------------------------------- ### Async take first n items from iterable Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Returns a list containing the first n items from an asynchronous iterable. If the iterable has fewer than n items, all available items are returned. If n is 0, an empty list is returned. Requires n to be non-negative. ```python import aioitertools.more_itertools async def example(): data = [1, 2, 3, 4, 5] first_two = await aioitertools.more_itertools.take(2, data) print(first_two) # Output: [1, 2] empty_list = await aioitertools.more_itertools.take(0, data) print(empty_list) # Output: [] ``` -------------------------------- ### Consume Iterable to Set with aioitertools.set Source: https://context7.com/omnilib/aioitertools/llms.txt Demonstrates consuming any iterable, including async generators, into a Python set using `aioitertools.set`. This function collects unique items. ```python import asyncio from aioitertools import set async def main(): result = await set([1, 2, 2, 3, 3, 3]) print(result) # {1, 2, 3} asyncio.run(main()) ``` -------------------------------- ### product - Async Cartesian product (Python) Source: https://context7.com/omnilib/aioitertools/llms.txt Yields the Cartesian product of input asynchronous iterables, equivalent to nested for-loops. This function is useful for generating all possible combinations of elements from multiple iterables. It also supports a `repeat` argument for products of a single iterable with itself. ```python import asyncio from aioitertools import product, list async def main(): # Product of two iterables result = await list(product('AB', '12')) print(result) # [('A', '1'), ('A', '2'), ('B', '1'), ('B', '2')] # Product with repeat result = await list(product([0, 1], repeat=3)) print(result) # [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] asyncio.run(main()) ``` -------------------------------- ### Yield results as they complete with as_completed Source: https://context7.com/omnilib/aioitertools/llms.txt The `as_completed` function from `aioitertools.asyncio` runs awaitables concurrently and yields their results as they finish. This differs from `asyncio.as_completed` as it yields the direct results, not futures. It requires `asyncio` and `aioitertools.asyncio`. ```python import asyncio from aioitertools.asyncio import as_completed async def fetch(url, delay): await asyncio.sleep(delay) return f"Result from {url}" async def main(): tasks = [ fetch("url1", 0.3), fetch("url2", 0.1), fetch("url3", 0.2), ] # Results arrive in completion order, not submission order async for result in as_completed(tasks): print(result) # Result from url2 # Result from url3 # Result from url1 # With timeout slow_tasks = [fetch(f"url{i}", i) for i in range(5)] try: async for result in as_completed(slow_tasks, timeout=2.5): print(result) except asyncio.TimeoutError: print("Timeout reached!") asyncio.run(main()) ``` -------------------------------- ### Conditional Iteration with aioitertools (takewhile/dropwhile) Source: https://context7.com/omnilib/aioitertools/llms.txt Provides `takewhile` to yield items as long as a predicate is true, and `dropwhile` to skip items while a predicate is true. Supports both synchronous and asynchronous predicates. ```python import asyncio from aioitertools import takewhile, dropwhile, list async def main(): data = [1, 2, 3, 4, 5, 1, 2, 3] # Take while less than 4 result = await list(takewhile(lambda x: x < 4, data)) print(result) # [1, 2, 3] # Drop while less than 4 result = await list(dropwhile(lambda x: x < 4, data)) print(result) # [4, 5, 1, 2, 3] # With async predicate async def async_pred(x): return x < 3 result = await list(takewhile(async_pred, [1, 2, 3, 4])) print(result) # [1, 2] asyncio.run(main()) ``` -------------------------------- ### Map Iterable with aioitertools.map Source: https://context7.com/omnilib/aioitertools/llms.txt Shows how `aioitertools.map` applies a function or coroutine to each item in an iterable. It supports both synchronous and asynchronous mapping functions. ```python import asyncio from aioitertools import map, list async def main(): # With standard function result = await list(map(lambda x: x * 2, range(5))) print(result) # [0, 2, 4, 6, 8] # With async function async def async_double(x): await asyncio.sleep(0.01) return x * 2 result = await list(map(async_double, range(5))) print(result) # [0, 2, 4, 6, 8] asyncio.run(main()) ``` -------------------------------- ### Running Accumulation with aioitertools.accumulate Source: https://context7.com/omnilib/aioitertools/llms.txt Performs a running accumulation on elements of an asynchronous iterable. Defaults to addition but can use other operators or custom asynchronous functions. ```python import asyncio import operator from aioitertools import accumulate, list async def main(): # Running sum result = await list(accumulate([1, 2, 3, 4, 5])) print(result) # [1, 3, 6, 10, 15] # Running product result = await list(accumulate([1, 2, 3, 4, 5], func=operator.mul)) print(result) # [1, 2, 6, 24, 120] # With async accumulator function async def async_add(a, b): return a + b result = await list(accumulate([1, 2, 3, 4], func=async_add)) print(result) # [1, 3, 6, 10] asyncio.run(main()) ``` -------------------------------- ### aioitertools.builtins.next Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Retrieves the next item from a mixed iterator, awaiting if necessary. Supports an optional default value. ```APIDOC ## async aioitertools.builtins.next(itr: Iterator | AsyncIterator, default: T2 = None) -> T1 | T2 ### Description Return the next item of any mixed iterator. Calls builtins.next() on standard iterators, and awaits itr._\_anext_\_() on async iterators. ### Method ASYNC FUNCTION ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python value = await next(it) ``` ### Response #### Success Response (T1 | T2) - **return_value** (T1 | T2) - The next item from the iterator, or the default value if provided and the iterator is exhausted. #### Response Example ```json ``` ``` -------------------------------- ### Find Minimum Value Asynchronously with aioitertools.builtins.min Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md The `aioitertools.builtins.min` function finds the smallest item in an asynchronous iterable. It accepts an optional `default` value and a `key` function for custom comparisons. It returns the smallest item or the default value if the iterable is empty. ```python import asyncio import aioitertools async def main(): result = await aioitertools.builtins.min(range(5)) print(f"The minimum value is: {result}") asyncio.run(main()) ``` -------------------------------- ### aioitertools.itertools.combinations_with_replacement Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Yields r length subsequences from the given iterable with replacement. This will consume the entire iterable before yielding values. ```APIDOC ## aioitertools.itertools.combinations_with_replacement ### Description 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. ### Method ASYNC FUNCTION ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python async for value in aioitertools.itertools.combinations_with_replacement("ABC", 2): print(value) # ("A", "A"), ("A", "B"), ("A", "C"), ("B", "B"), ... ``` ### Response #### Success Response (200) Yields combinations with replacement as tuples. #### Response Example ``` ('A', 'A') ('A', 'B') ('A', 'C') ('B', 'B') ('B', 'C') ('C', 'C') ``` ``` -------------------------------- ### Find Min/Max Values in Iterable with aioitertools Source: https://context7.com/omnilib/aioitertools/llms.txt Finds the minimum or maximum value within an asynchronous iterable. Supports a key function for custom comparisons and a default value for empty iterables. ```python import asyncio from aioitertools import min, max async def main(): numbers = [3, 1, 4, 1, 5, 9, 2, 6] smallest = await min(numbers) print(smallest) # 1 largest = await max(numbers) print(largest) # 9 # With key function words = ['apple', 'pie', 'strawberry'] longest = await max(words, key=len) print(longest) # 'strawberry' # With default for empty iterable result = await min([], default=0) print(result) # 0 asyncio.run(main()) ``` -------------------------------- ### Asyncio Gather with Concurrency Limit (Python) Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Implements asyncio.gather with an added limit for concurrent task execution. It buffers all results and ensures cancellation of pending tasks if the gather operation is cancelled. Accepts awaitable objects as arguments. ```python import asyncio from aioitertools.asyncio import gather async def some_coro(i): await asyncio.sleep(1) return i async def main(): futures = [some_coro(i) for i in range(10)] results = await gather(*futures, limit=2) print(results) asyncio.run(main()) ``` -------------------------------- ### Async Zip with Typed Iterables Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Combines elements from up to five typed iterables (synchronous or asynchronous) into an async iterator of tuples. The iteration stops when the shortest iterable is exhausted. This function is useful for parallel processing of data from different sources. ```python import aioitertools async def example(i, j, k): async for a, b, c in aioitertools.builtins.zip(i, j, k): # Process elements a, b, and c pass ``` -------------------------------- ### Async Zip with Any Iterables Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Combines elements from multiple iterables (synchronous or asynchronous) of any type into an async iterator of tuples. It accepts a variable number of iterables, including a special `__iterables` argument for a collection of iterables. The iteration stops when the shortest iterable is exhausted. ```python import aioitertools async def example(iter1, iter2, *more_iters): async for result_tuple in aioitertools.builtins.zip(iter1, iter2, *more_iters): # Process the combined tuple pass async def example_with_list(list_of_iters): async for result_tuple in aioitertools.builtins.zip(*list_of_iters): # Process the combined tuple pass ``` -------------------------------- ### aioitertools.builtins.min Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Returns the smallest item in an iterable or the smallest of two or more arguments. It supports both synchronous and asynchronous iterables. ```APIDOC ## async aioitertools.builtins.min ### Description Return the smallest item in an iterable or the smallest of two or more arguments. ### Method ASYNC FUNCTION ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python await min(range(5)) ``` ### Response #### Success Response (200) - **Return type:** Orderable | T - The smallest item found in the iterable or arguments. #### Response Example ```json 0 ``` ``` -------------------------------- ### Async Combinations Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Yields r-length subsequences from the given iterable. This function is a simple wrapper around itertools.combinations and is designed for asyncio. It consumes the entire iterable before yielding any values. ```python import aioitertools async for value in aioitertools.itertools.combinations(range(4), 3): print(value) # Output: (0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3) ``` -------------------------------- ### Generate Cartesian Products Asynchronously with aioitertools Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Yields cartesian products of all provided iterables. This is a wrapper around itertools.combinations for asyncio and consumes all iterables before yielding values. ```python 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.builtins.min Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Finds the smallest item in a mixed iterable (synchronous or asynchronous) or among multiple arguments. ```APIDOC ## aioitertools.builtins.min(itr, *, key=None) ### Description Return the smallest item in an iterable or the smallest of two or more arguments. ### Method ASYNC FUNCTION ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **itr** (Iterable | AsyncIterable) - The input iterable. * **key** (Callable | None, optional) - A function to specify the comparison key. Defaults to None. ### Request Example ```python await min(range(5)) ``` ### Response #### Success Response (200) * **Orderable** (Any) - The smallest item found in the iterable or among the arguments. #### Response Example ```json 0 ``` ``` -------------------------------- ### Concurrency-limited gather with gather Source: https://context7.com/omnilib/aioitertools/llms.txt The `gather` function from `aioitertools.asyncio` is similar to `asyncio.gather` but allows for an optional `limit` parameter to control the number of concurrently executing tasks. This is useful for rate limiting or managing resource usage. It requires `asyncio` and `aioitertools.asyncio`. ```python import asyncio from aioitertools.asyncio import gather async def fetch(n): print(f"Starting {n}") await asyncio.sleep(0.1) print(f"Finished {n}") return n * 10 async def main(): # Run all concurrently results = await gather(*[fetch(i) for i in range(5)]) print(results) # [0, 10, 20, 30, 40] # Limit to 2 concurrent tasks print("\nWith limit=2:") results = await gather(*[fetch(i) for i in range(5)], limit=2) print(results) # [0, 10, 20, 30, 40] # Handle exceptions async def may_fail(n): if n == 2: raise ValueError("Failed!") return n results = await gather(*[may_fail(i) for i in range(5)], return_exceptions=True) print(results) # [0, 1, ValueError('Failed!'), 3, 4] asyncio.run(main()) ``` -------------------------------- ### compress - Async select items using selectors (Python) Source: https://context7.com/omnilib/aioitertools/llms.txt Yields elements from an asynchronous iterable when the corresponding selector in another iterable is truthy. This function is useful for filtering elements based on a boolean mask or a list of selectors. ```python import asyncio from aioitertools import compress, list async def main(): data = ['a', 'b', 'c', 'd', 'e'] selectors = [1, 0, 1, 0, 1] result = await list(compress(data, selectors)) print(result) # ['a', 'c', 'e'] asyncio.run(main()) ``` -------------------------------- ### Yield results from async iterables with aioitertools.asyncio.as_generated Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Yields results from one or more asynchronous iterables in the order they are produced. It creates separate tasks for each iterable and a single queue for results. If 'return_exceptions' is True, exceptions are yielded as results; otherwise, they are raised and pending tasks are cancelled. ```python3 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 ``` -------------------------------- ### Combine Iterables Sequentially with aioitertools.chain Source: https://context7.com/omnilib/aioitertools/llms.txt Chains multiple asynchronous iterables together to yield elements sequentially. Includes `chain.from_iterable` for handling an iterable of iterables. ```python import asyncio from aioitertools import chain, list async def main(): # Chain multiple iterables result = await list(chain([1, 2], [3, 4], [5, 6])) print(result) # [1, 2, 3, 4, 5, 6] # Chain from iterable of iterables iterables = [[1, 2], [3, 4], [5, 6]] result = await list(chain.from_iterable(iterables)) print(result) # [1, 2, 3, 4, 5, 6] asyncio.run(main()) ``` -------------------------------- ### aioitertools.itertools.combinations Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Yields r length subsequences from the given iterable. This will consume the entire iterable before yielding values. ```APIDOC ## aioitertools.itertools.combinations ### Description Yield r length subsequences from the given iterable. Simple wrapper around itertools.combinations for asyncio. This will consume the entire iterable before yielding values. ### Method ASYNC FUNCTION ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python async for value in aioitertools.itertools.combinations(range(4), 3): print(value) # (0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3) ``` ### Response #### Success Response (200) Yields combinations as tuples. #### Response Example ``` (0, 1, 2) (0, 1, 3) (0, 2, 3) (1, 2, 3) ``` ``` -------------------------------- ### aioitertools.builtins.list Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Consumes a mixed iterable and returns its elements as a list. ```APIDOC ## async aioitertools.builtins.list(itr) ### Description Consume a mixed iterable and return a list of items in order. ### Method ASYNC FUNCTION ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python await list(range(5)) -> [0, 1, 2, 3, 4] ``` ### Response #### Success Response (list) - **return_value** (list) - A list containing all items from the iterable. #### Response Example ```json [0, 1, 2, 3, 4] ``` ``` -------------------------------- ### Async tee for duplicating iterables Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Creates n independent asynchronous iterators from a single asynchronous iterable. Each iterator will yield the same sequence of items. This is useful when you need to consume the same sequence multiple times. Be mindful of memory usage and potential blocking if iterators are consumed at different rates. ```python import aioitertools.itertools async def example(): it1, it2 = aioitertools.itertools.tee(range(5), n=2) async for value in it1: print(f"it1: {value}") async for value in it2: print(f"it2: {value}") ``` -------------------------------- ### Asynchronously Zip Iterables with aioitertools.builtins.zip Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md The `aioitertools.builtins.zip` function takes one or more asynchronous iterables and returns an asynchronous iterator that aggregates elements from each of the iterables. It yields tuples where the i-th tuple contains the i-th element from each of the argument iterables. The iteration stops when the shortest input iterable is exhausted. ```python import asyncio import aioitertools async def main(): async_list1 = aioitertools.iter([1, 2, 3]) async_list2 = aioitertools.iter(['a', 'b', 'c']) zipped_iterator = aioitertools.builtins.zip(async_list1, async_list2) async for item in zipped_iterator: print(item) asyncio.run(main()) ``` -------------------------------- ### aioitertools.asyncio.as_generated Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Yields results from one or more asynchronous iterables in the order they are produced. It creates tasks to drain each iterable and a single queue for results. ```APIDOC ## async aioitertools.asyncio.as_generated(iterables, return_exceptions=False) ### Description Yields results from one or more async iterables, in the order they are produced. This is similar to `as_completed()` but for async iterators or generators. If `return_exceptions` is `True`, exceptions are yielded as results; otherwise, they are raised. ### Method GET ### Endpoint /omnilib/aioitertools/asyncio/as_generated ### Parameters #### Path Parameters None #### Query Parameters - **iterables** (Iterable[AsyncIterable[T]]) - Required - An iterable of asynchronous iterables to process. - **return_exceptions** (bool) - Optional - If True, exceptions are yielded as results. Defaults to False. #### Request Body None ### Request Example ```python # Example usage (conceptual) async def generator(x): for i in range(x): yield i gen1 = generator(3) gen2 = generator(2) async for value in as_generated([gen1, gen2]): print(value) # Values will be intermixed, e.g., 0, 0, 1, 1, 2 ``` ### Response #### Success Response (200) - **value** (T) - A value yielded from one of the asynchronous iterables. #### Response Example ```json { "value": 0 } ``` ``` -------------------------------- ### Split iterable based on predicate with aioitertools.more_itertools.before_and_after Source: https://github.com/omnilib/aioitertools/blob/main/docs/api.md Splits an iterable into two parts: one containing elements before a condition is met, and another containing the rest. It's a variant of takewhile that provides access to the remainder of the iterator. Note that the first iterator must be fully consumed before the second can yield valid results. ```python3 it = iter('ABCdEfGhI') all_upper, remainder = await before_and_after(str.isupper, it) ''.join([char async for char in all_upper]) ''.join([char async for char in remainder]) ``` -------------------------------- ### Gather from an iterable with gather_iter Source: https://context7.com/omnilib/aioitertools/llms.txt The `gather_iter` function from `aioitertools.asyncio` is a wrapper around `gather` that accepts an iterable of awaitables instead of using `*args`. The values within the iterable do not necessarily have to be awaitable. It requires `asyncio` and `aioitertools.asyncio`. ```python import asyncio from aioitertools.asyncio import gather_iter async def process(x): await asyncio.sleep(0.01) return x * 2 async def main(): tasks = [process(i) for i in range(5)] results = await gather_iter(tasks, limit=2) print(results) # [0, 2, 4, 6, 8] asyncio.run(main()) ``` -------------------------------- ### Test Truthiness of Items with aioitertools (all/any) Source: https://context7.com/omnilib/aioitertools/llms.txt Checks if all or any elements in an asynchronous iterable are truthy. Automatically awaits any awaitable elements present in the iterable. ```python import asyncio from aioitertools import all, any async def main(): # all - True if all items are truthy result = await all([True, True, True]) print(result) # True result = await all([True, False, True]) print(result) # False # any - True if any item is truthy result = await any([False, False, True]) print(result) # True result = await any([False, False, False]) print(result) # False asyncio.run(main()) ```