### Create async context manager from generator Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt A decorator to create asynchronous context managers from asynchronous generator functions. Ensures setup and teardown logic is executed correctly. ```python import asyncstdlib as a @a.contextmanager async def managed_resource(name: str): print(f"Acquiring {name}") try: yield f"resource:{name}" finally: print(f"Releasing {name}") async def example(): async with managed_resource("database") as resource: print(f"Using {resource}") # Output: # Acquiring database # Using resource:database # Releasing database # Also works as decorator @managed_resource("connection") async def do_work(): return "done" result = await do_work() # Acquiring connection # Releasing connection ``` -------------------------------- ### sum - Sum elements of iterable Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Sums all elements in an async iterable, with an optional start value. ```APIDOC ## sum ### Description Sums all elements in an async iterable, with optional start value. ### Parameters #### Arguments - **iterable** (async iterable) - Required - The iterable to sum. - **start** (number) - Optional - The starting value for the sum. ``` -------------------------------- ### Sum elements of an iterable Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Sums all elements in an async iterable, with an optional start value. ```python import asyncstdlib as a async def example(): numbers = [1, 2, 3, 4, 5] # Basic sum total = await a.sum(numbers) print(total) # 15 # With start value total = await a.sum(numbers, start=10) print(total) # 25 # Works with async iterables async def prices(): yield 10.50 yield 20.25 yield 5.75 total = await a.sum(prices()) print(f"Total: ${total:.2f}") # Total: $36.50 ``` -------------------------------- ### Enumerate async iterables Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Creates an async iterator of (index, item) tuples from an iterable, supporting custom start indices and async iterables. ```python import asyncstdlib as a async def example(): items = ["apple", "banana", "cherry"] # Basic usage async for idx, item in a.enumerate(items): print(f"{idx}: {item}") # 0: apple, 1: banana, 2: cherry # With custom start async for idx, item in a.enumerate(items, start=1): print(f"Item #{idx}: {item}") # Item #1: apple, Item #2: banana, Item #3: cherry # Works with async iterables async def async_items(): yield "x" yield "y" async for idx, item in a.enumerate(async_items()): print(f"{idx}: {item}") ``` -------------------------------- ### enumerate - Async enumerate with counter Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Creates an async iterator of (index, item) tuples from an iterable, with an optional start index. ```APIDOC ## enumerate ### Description Creates an async iterator of (index, item) tuples from an iterable, with optional start index. ### Parameters #### Arguments - **iterable** (iterable) - Required - The iterable to enumerate. - **start** (int) - Optional - The starting index value (default 0). ``` -------------------------------- ### Slice async iterators Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Creates an async iterator over a specific slice of items, supporting start, stop, and step parameters. ```python import asyncstdlib as a async def example(): numbers = range(100) # First 5 items async for item in a.islice(numbers, 5): print(item) # 0, 1, 2, 3, 4 # Items 10-15 result = await a.list(a.islice(numbers, 10, 15)) print(result) # [10, 11, 12, 13, 14] # Every 2nd item from first 10 result = await a.list(a.islice(numbers, 0, 10, 2)) print(result) # [0, 2, 4, 6, 8] # Skip first 5, take rest async def infinite_gen(): i = 0 while True: yield i i += 1 result = await a.list(a.islice(infinite_gen(), 5, 10)) print(result) # [5, 6, 7, 8, 9] ``` -------------------------------- ### Build Documentation with Sphinx Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/devel/contributing.rst Generate HTML documentation locally to preview changes. Open the generated index.html file in your browser to view the documentation. ```bash sphinx-build -M html ./docs ./docs/_build ``` -------------------------------- ### Uniform Iteration with any_iter Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Demonstrates handling different iteration patterns (async, awaitable, sync) uniformly using any_iter. ```python async def async_iter(n): for i in range(n): yield i async def await_iter(n): return list(range(n)) def sync_iter(n): return range(n) async def example(): # any_iter handles all patterns uniformly some_iter = random.choice([async_iter, await_iter, sync_iter]) async for item in a.any_iter(some_iter(5)): print(item) # Works regardless of which function was chosen ``` -------------------------------- ### Iterating and Checking Cleanup with asyncstdlib Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/notes/iter_scope.rst Demonstrates using `a.zip` to iterate over a limited number of items from an infinite async iterator and then checks if the iterator is closed using `a.anext`. ```python3 import asyncio import asyncstdlib as a async def async_squares(i=0): """Provide an infinite stream of squared numbers""" while True: await asyncio.sleep(0.1) yield i**2 i += 1 async def main(): async_iter = async_squares() # loop until we are done async for i, s in a.zip(range(5), async_iter): print(f"{i}: {s}") assert await a.anext(async_iter, "Closed!") == "Closed!" asyncio.run(main()) ``` -------------------------------- ### Run Black, Flake8, and Pytest Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/devel/contributing.rst Execute code formatting, linting, and testing locally. Ensure these basic checks pass before submitting changes. ```bash python -m black asyncstdlib unittests python -m flake8 asyncstdlib unittests python -m pytest ``` -------------------------------- ### Async Commands for Event Loop Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/devel/testloop.rst Provides details on custom async commands like `Schedule`, `Switch`, and `Lock` used with the test event loop. ```APIDOC ## Async Commands ### Description Custom asynchronous commands designed for use with the test event loop. ### Commands - **Schedule(*await Any)**: Represents a scheduling operation. - **Switch(skip: int, /)**: A command to skip a specified number of operations. - **Switch(min: int, max: int, /)**: A command to switch within a specified range. - **Switch()**: A general Switch command. - **Lock**: Represents a lock mechanism for synchronization. ### Method N/A (These are classes/constructors for async operations) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python # Example usage (conceptual) from asyncstdlib.testing import Schedule, Switch, Lock # await Schedule(some_coroutine()) # await Switch(skip=5) # await Switch(min=0, max=10) # await Lock() ``` ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Run Mypy and Pyright for Type Checking Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/devel/contributing.rst Perform comprehensive type checking using mypy and pyright. This is crucial for major typing-related changes. ```bash python -m mypy --pretty python -m pyright ``` -------------------------------- ### ExitStack Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/contextlib.rst A context manager for managing multiple asynchronous context managers. ```APIDOC ## ExitStack ### Description An asynchronous context manager that manages a stack of other asynchronous context managers. It ensures that all entered contexts are properly exited, even if errors occur. ### Methods - **enter_context(cm)**: Enter an asynchronous context manager and push it onto the stack. - **callback(callback, *args, **kwargs)**: Register a callback to be run when the stack is closed. - **push(exit)**: Push an exit function or object onto the stack. - **pop_all()**: Pop all context managers from the stack and return them as a list. - **aclose()**: Close all context managers currently on the stack. ### Version Added 1.1.0 ``` -------------------------------- ### Manage dynamic context managers with ExitStack Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt ExitStack allows programmatic management of a dynamic number of context managers. It supports entering multiple contexts and registering cleanup callbacks. ```python import asyncstdlib as a async def example(): async with a.ExitStack() as stack: # Enter context managers dynamically @a.contextmanager async def resource(name): print(f"Enter {name}") yield name print(f"Exit {name}") # Enter multiple contexts r1 = await stack.enter_context(resource("db")) r2 = await stack.enter_context(resource("cache")) print(f"Using {r1} and {r2}") # Register cleanup callbacks stack.callback(print, "Cleanup callback executed") # Output: # Enter db # Enter cache # Using db and cache # Cleanup callback executed # Exit cache # Exit db ``` -------------------------------- ### Await Arguments and Apply Function Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Await multiple awaitables and apply a function to their results, supporting both positional and keyword arguments. ```python import asyncstdlib as a async def get_x(): return 10 async def get_y(): return 5 async def example(): # Await args and apply function result = await a.apply(lambda x, y: x + y, get_x(), get_y()) print(result) # 15 # With keyword arguments async def get_base(): return 2 async def get_exp(): return 8 result = await a.apply(pow, get_base(), get_exp()) print(result) # 256 ``` -------------------------------- ### nullcontext Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/contextlib.rst Return an asynchronous context manager that does nothing. ```APIDOC ## nullcontext ### Description Returns an asynchronous context manager that does nothing when entering or exiting. It yields the provided `enter_result` upon entering the context. ### Usage ```python async with nullcontext(some_value) as value: # 'value' will be 'some_value' pass ``` ``` -------------------------------- ### contextmanager Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/contextlib.rst A decorator to create asynchronous context managers from generator functions. ```APIDOC ## contextmanager ### Description A decorator that transforms a generator function into an asynchronous context manager. The generator function should yield once. The code before the yield is executed when entering the context, and the code after the yield is executed when exiting. ### Version Added 3.12.2 ### Note The created context manager is a `~.ContextDecorator`. ``` -------------------------------- ### all / any - Test truth of iterable elements Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Async versions of built-in all and any that work with async iterables, supporting short-circuiting. ```APIDOC ## all / any ### Description Async versions of built-in all and any that work with async iterables. Short-circuit when result is determined. ### Parameters #### Arguments - **iterable** (async iterable) - Required - The iterable to evaluate. ``` -------------------------------- ### Running accumulation Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Generates an async iterator of accumulated values, useful for running totals, products, or max values. ```python import asyncstdlib as a import operator async def example(): numbers = [1, 2, 3, 4, 5] # Running sum (default) result = await a.list(a.accumulate(numbers)) print(result) # [1, 3, 6, 10, 15] # Running product result = await a.list(a.accumulate(numbers, operator.mul)) print(result) # [1, 2, 6, 24, 120] # With initial value result = await a.list(a.accumulate(numbers, initial=10)) print(result) # [10, 11, 13, 16, 20, 25] # Running max values = [3, 1, 4, 1, 5, 9, 2, 6] result = await a.list(a.accumulate(values, max)) print(result) # [3, 3, 4, 4, 5, 9, 9, 9] ``` -------------------------------- ### AbstractContextManager Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/contextlib.rst An abstract base class for asynchronous context managers. Classes inheriting from this must implement __aenter__. ```APIDOC ## AbstractContextManager ### Description An abstract base class for asynchronous context managers. A class may inherit from `AbstractContextManager`, in which case it must implement an `__aenter__` method; the default `__aenter__` returns the asynchronous context manager itself. ### Version Added 1.1.0 ``` -------------------------------- ### asyncstdlib.heapq.nsmallest Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/heapq.rst Returns a list with the n smallest elements from the dataset defined by iterables. Supports an optional key function. ```APIDOC ## asyncstdlib.heapq.nsmallest ### Description Returns a list containing the n smallest elements from the input iterables. Supports an optional asynchronous key function. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **[T, ...]** (list) - A list of the n smallest elements. #### Response Example N/A ``` -------------------------------- ### min / max - Find minimum/maximum value Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Find the minimum or maximum value in an async iterable, with optional key function and default value. ```APIDOC ## min / max ### Description Find the minimum or maximum value in an async iterable, with optional key function and default value. ### Parameters #### Arguments - **iterable** (async iterable) - Required - The iterable to search. - **key** (callable) - Optional - Function to extract comparison key. - **default** (any) - Optional - Value to return if iterable is empty. ``` -------------------------------- ### iter - Create async iterator Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Creates an async iterator from regular iterables, async iterables, or a callable with a sentinel value. ```APIDOC ## iter ### Description Converts various input types into an async iterator. Supports regular iterables, async iterables, or a callable/sentinel pair. ### Parameters #### Arguments - **iterable** (Iterable/AsyncIterable/Callable) - Required - The source to iterate over. - **sentinel** (Any) - Optional - The value that signals the end of iteration when using a callable. ``` -------------------------------- ### Wrap Synchronous Functions Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Wraps a synchronous function to be awaitable, allowing uniform handling of sync and async functions. ```python import asyncstdlib as a def sync_function(x, y): return x * y async def async_function(x): return x ** 2 async def example(): # Wrap sync function wrapped = a.sync(sync_function) result = await wrapped(3, 4) print(result) # 12 # Already async functions pass through unchanged wrapped = a.sync(async_function) result = await wrapped(5) print(result) # 25 # Useful for uniform handling funcs = [sync_function, async_function] for func in funcs: wrapped = a.sync(lambda: func(2, 2) if func == sync_function else func(2)) # Both can now be awaited ``` -------------------------------- ### Create async iterator with iter Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Converts regular iterables, async iterables, or callables with a sentinel into an async iterator. ```python import asyncstdlib as a async def example(): # From regular list async for item in a.iter([1, 2, 3]): print(item) # 1, 2, 3 # From async generator async def async_gen(): yield "a" yield "b" async for item in a.iter(async_gen()): print(item) # "a", "b" # With callable and sentinel (like built-in iter) counter = iter(range(5)).__next__ async for item in a.iter(counter, 3): print(item) # 0, 1, 2 (stops when sentinel 3 is reached) ``` -------------------------------- ### list / tuple / set / dict - Collect to containers Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Collect all items from an async iterable into standard Python containers. ```APIDOC ## list / tuple / set / dict ### Description Collect all items from an async iterable into standard Python containers. ### Parameters #### Arguments - **iterable** (async iterable) - Required - The source of items. - **kwargs** (dict) - Optional - Additional keyword arguments for dict construction. ``` -------------------------------- ### closing Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/contextlib.rst Return a context manager that closes the given object. ```APIDOC ## closing ### Description Returns an asynchronous context manager that ensures the `aclose` method (or `close` if `aclose` is not present) of the given object is called upon exiting the context. ### Usage ```python async with closing(my_async_resource) as resource: # Use the resource ``` ``` -------------------------------- ### Apply function to argument tuples with starmap Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Applies a function to arguments unpacked from an iterable of argument tuples. Supports both regular and asynchronous functions. ```python import asyncstdlib as a async def example(): # Each item is a tuple of arguments coordinates = [(0, 0), (1, 1), (3, 4)] def distance(x, y): return (x**2 + y**2) ** 0.5 result = await a.list(a.starmap(distance, coordinates)) print(result) # [0.0, 1.414..., 5.0] # With async function async def async_power(base, exp): return base ** exp args = [(2, 3), (3, 2), (10, 2)] result = await a.list(a.starmap(async_power, args)) print(result) # [8, 9, 100] ``` -------------------------------- ### Infinite cycling Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Creates an infinite async iterator that cycles through the provided items. Use with islice to limit the output. ```python import asyncstdlib as a async def example(): colors = ["red", "green", "blue"] # Cycle infinitely (use islice to limit) async for i, color in a.enumerate(a.islice(a.cycle(colors), 7)): print(f"{i}: {color}") # 0: red, 1: green, 2: blue, 3: red, 4: green, 5: blue, 6: red # Items are buffered for subsequent cycles async def slow_gen(): for i in range(3): yield i result = await a.list(a.islice(a.cycle(slow_gen()), 9)) print(result) # [0, 1, 2, 0, 1, 2, 0, 1, 2] ``` -------------------------------- ### Aggregate iterables with async zip Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Combines multiple sync or async iterables into tuples. Use strict=True to raise a ValueError if input lengths differ. ```python import asyncstdlib as a async def example(): names = ["Alice", "Bob", "Charlie"] async def async_scores(): yield 95 yield 87 yield 92 # Mix sync and async iterables async for name, score in a.zip(names, async_scores()): print(f"{name}: {score}") # Output: Alice: 95, Bob: 87, Charlie: 92 # Strict mode raises ValueError if lengths differ try: async for x, y in a.zip([1, 2], [1, 2, 3], strict=True): pass except ValueError as e: print(f"Length mismatch: {e}") ``` -------------------------------- ### Use nullcontext as a placeholder Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Use nullcontext as a neutral context manager when a context manager is optional. It can also be used with enter_result to provide a default value. ```python import asyncstdlib as a import asyncio async def example(): # Use as placeholder when context manager is optional async def process(data, use_lock=False): lock = asyncio.Lock() if use_lock else a.nullcontext() async with lock: return data * 2 result = await process(5, use_lock=False) print(result) # 10 # With enter_result async with a.nullcontext("default_value") as value: print(value) # default_value ``` -------------------------------- ### Test truth of iterable elements with all/any Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Async versions of built-in all and any that short-circuit when the result is determined. ```python import asyncstdlib as a async def example(): # all - True if all elements are truthy result = await a.all([True, True, True]) print(result) # True result = await a.all([True, False, True]) print(result) # False (short-circuits on False) # any - True if any element is truthy result = await a.any([False, False, True]) print(result) # True (short-circuits on True) # With async iterables async def checks(): yield True yield False result = await a.all(checks()) print(result) # False ``` -------------------------------- ### Async Transforming Utilities Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/asynctools.rst Functions for transforming and applying asynchronous operations to iterables and functions. ```APIDOC ## sync(function: (...) -> (await) T) -> (...) -> await T ### Description Wraps a function to ensure it handles awaitable return values correctly. ## any_iter(iter: (await) (async) iter (await) T) ### Description Normalizes an iterator that may contain awaitable items or be an asynchronous iterator itself. ## await_each(awaitables: iter await T) ### Description Iterates over a collection of awaitables and yields their results. ## apply(func: (*T, **T) -> R, *args: await T, **kwargs: await T) -> R ### Description Asynchronously applies a function to a set of awaitable arguments and keyword arguments. ``` -------------------------------- ### Standard Types Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/builtins.rst Provides asynchronous versions of standard Python types like dict, list, set, tuple, and sorted. ```APIDOC ## dict(iterable: (async) iter (str, T) = ()) -> {str: T, ...} ### Description Asynchronously creates a new dictionary with keys from iterable and values equal to value. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **{str: T, ...}** (dict) - A dictionary created from the iterable. #### Response Example None ## list(iterable: (async) iter T = ()) -> [T, ...] ### Description Asynchronously creates a new list with elements from the iterable. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **[T, ...]** (list) - A list created from the iterable. #### Response Example None ## set(iterable: (async) iter T = ()) -> {T, ...} ### Description Asynchronously creates a new set with elements from the iterable. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **{T, ...}** (set) - A set created from the iterable. #### Response Example None ## tuple(iterable: (async) iter T = ()) -> (T, ...) ### Description Asynchronously creates a new tuple with elements from the iterable. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **(T, ...)** (tuple) - A tuple created from the iterable. #### Response Example None ## sorted(iterable: (async) iter T, *, key: (T) → (await) Any, reverse: bool) -> [T, ...] ### Description Asynchronously returns a new sorted list from the items in iterable. ### Version Added 3.9.0 ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **[T, ...]** (list) - A new sorted list. #### Response Example None ``` -------------------------------- ### zip - Async zip for multiple iterables Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Aggregates elements from multiple iterables into tuples, supporting both sync and async iterables. ```APIDOC ## zip ### Description Aggregates elements from multiple iterables into tuples. Works with mixed sync and async iterables. ### Parameters #### Arguments - **iterables** (Iterable/AsyncIterable) - Required - One or more iterables to aggregate. - **strict** (bool) - Optional - If True, raises ValueError if iterables have different lengths. ``` -------------------------------- ### Collect items into containers Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Collects items from an async iterable into standard Python containers like list, tuple, set, or dict. ```python import asyncstdlib as a async def example(): async def async_items(): yield 1 yield 2 yield 3 yield 2 # duplicate # Collect to list items = await a.list(async_items()) print(items) # [1, 2, 3, 2] # Collect to tuple items = await a.tuple(async_items()) print(items) # (1, 2, 3, 2) # Collect to set (removes duplicates) items = await a.set(async_items()) print(items) # {1, 2, 3} # Collect to dict (from key-value pairs) async def key_values(): yield ("a", 1) yield ("b", 2) mapping = await a.dict(key_values()) print(mapping) # {'a': 1, 'b': 2} # Dict with additional kwargs mapping = await a.dict(key_values(), c=3) print(mapping) # {'a': 1, 'b': 2, 'c': 3} ``` -------------------------------- ### Infinite Iterators Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/itertools.rst Functions for creating infinite iterators. ```APIDOC ## cycle(iterable) ### Description Creates an infinite iterator that cycles through the provided (async) iterable. ### Parameters #### Request Body - **iterable** ((async) iter T) - Required - The source iterable to cycle. ``` -------------------------------- ### reduce(function, iterable, initial) Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/functools.rst Reduces an async iterable to a single value using an async function. ```APIDOC ## reduce(function, iterable, initial) ### Description Applies a function of two arguments cumulatively to the items of an iterable, from left to right, so as to reduce the iterable to a single value. ### Parameters - **function** ((T, T) -> (await) T) - Required - The function to apply. - **iterable** ((async) iter T) - Required - The async iterable to reduce. - **initial** (T) - Optional - The initial value for the reduction. ``` -------------------------------- ### Find minimum or maximum value Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Finds the minimum or maximum value in an async iterable, supporting optional key functions and default values. ```python import asyncstdlib as a async def example(): numbers = [3, 1, 4, 1, 5, 9, 2, 6] # Basic usage minimum = await a.min(numbers) maximum = await a.max(numbers) print(f"Min: {minimum}, Max: {maximum}") # Min: 1, Max: 9 # With key function words = ["apple", "pie", "banana"] longest = await a.max(words, key=len) shortest = await a.min(words, key=len) print(f"Longest: {longest}, Shortest: {shortest}") # Longest: banana, Shortest: pie # With default for empty iterables result = await a.min([], default=0) print(result) # 0 # Async key function async def get_score(name): scores = {"Alice": 95, "Bob": 87} return scores.get(name, 0) best = await a.max(["Alice", "Bob"], key=get_score) print(best) # Alice ``` -------------------------------- ### Use builtin property for async attributes Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/notes/compatible.rst Demonstrates using the standard library @property decorator to wrap an async method, allowing for asynchronous attribute access. ```python3 # python3 -m asyncio class Remote: _count = 0 @property # <== builtin @property ... async def attribute(self): # ... around an async method await asyncio.sleep(1) # let's pretend to do some work... self._count += 1 return "Na" * self._count instance = Remote() print(await instance.attribute) # waits 1 second, prints Na print(await instance.attribute) # waits 1 second, prints NaNa ``` -------------------------------- ### Sync Decorator for Test Cases Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/devel/testloop.rst The `sync` decorator allows async test cases to be run in an event loop agnostic manner, compatible with pytest. ```APIDOC ## Sync Decorator ### Description A decorator compatible with pytest that allows `async def` test cases to be run within an event loop. ### Method Decorator ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python from asyncstdlib as a @a.sync async def test_something(): assert True ``` ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Apply functions to iterables with async map Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Applies a sync or async function to items from one or more iterables. Async functions are automatically awaited. ```python import asyncstdlib as a async def example(): numbers = [1, 2, 3, 4, 5] # With sync function async for squared in a.map(lambda x: x ** 2, numbers): print(squared) # 1, 4, 9, 16, 25 # With async function async def fetch_data(id): return f"data_{id}" async for data in a.map(fetch_data, [1, 2, 3]): print(data) # data_1, data_2, data_3 # Multiple iterables (like built-in map) async for result in a.map(lambda x, y: x + y, [1, 2], [10, 20]): print(result) # 11, 22 ``` -------------------------------- ### asyncstdlib.heapq.nlargest Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/heapq.rst Returns a list with the n largest elements from the dataset defined by iterables. Supports an optional key function. ```APIDOC ## asyncstdlib.heapq.nlargest ### Description Returns a list containing the n largest elements from the input iterables. Supports an optional asynchronous key function. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **[T, ...]** (list) - A list of the n largest elements. #### Response Example N/A ``` -------------------------------- ### Create decorator context managers with ContextDecorator Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt ContextDecorator is a base class for context managers that can also be used as decorators. It simplifies the creation of context managers usable in both 'async with' statements and as decorators. ```python import asyncstdlib as a import time import asyncio class TimingContext(a.ContextDecorator): def __init__(self, name: str): self.name = name self.start = None async def __aenter__(self): self.start = time.time() print(f"Starting {self.name}") return self async def __aexit__(self, *exc): elapsed = time.time() - self.start print(f"{self.name} took {elapsed:.3f}s") async def example(): # As context manager async with TimingContext("operation"): await asyncio.sleep(0.1) # As decorator @TimingContext("function") async def slow_function(): await asyncio.sleep(0.1) return "result" result = await slow_function() ``` -------------------------------- ### Compress data using boolean selectors Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Filters data based on a boolean selector iterable. Works with any truthy/falsy values for selectors. ```python import asyncstdlib as a async def example(): data = ["A", "B", "C", "D", "E"] selectors = [True, False, True, False, True] result = await a.list(a.compress(data, selectors)) print(result) # ['A', 'C', 'E'] # Selectors can be any truthy/falsy values selectors = [1, 0, 1, 0, 1] result = await a.list(a.compress(data, selectors)) print(result) # ['A', 'C', 'E'] ``` -------------------------------- ### LRUAsyncCallable Methods Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/functools.rst Methods available on the object returned by lru_cache. ```APIDOC ## LRUAsyncCallable Methods ### Methods - **cache_clear()** - Clears all entries from the cache. - **cache_discard(...)** - Discards a specific entry from the cache based on arguments. - **cache_info()** - Returns a dictionary containing hits, misses, maxsize, and current size. - **cache_parameters()** - Returns the configuration parameters of the cache. ``` -------------------------------- ### Filter items with async filter Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Yields items from an iterable that satisfy a sync or async predicate. Passing None as the predicate filters out falsy values. ```python import asyncstdlib as a async def example(): numbers = range(10) # Sync predicate async for even in a.filter(lambda x: x % 2 == 0, numbers): print(even) # 0, 2, 4, 6, 8 # Async predicate async def is_valid(x): return x > 5 async for valid in a.filter(is_valid, numbers): print(valid) # 6, 7, 8, 9 # None as predicate filters falsy values items = [0, 1, "", "hello", None, [], [1, 2]] async for truthy in a.filter(None, items): print(truthy) # 1, "hello", [1, 2] ``` -------------------------------- ### Find N Largest or Smallest Items Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Efficiently finds the n largest or smallest items from an async iterable, supporting custom key functions. ```python import asyncstdlib as a async def example(): numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] # Find 3 largest largest = await a.nlargest(numbers, 3) print(largest) # [9, 6, 5] # Find 3 smallest smallest = await a.nsmallest(numbers, 3) print(smallest) # [1, 1, 2] # With key function words = ["apple", "pie", "banana", "fig", "cherry"] longest = await a.nlargest(words, 2, key=len) print(longest) # ['banana', 'cherry'] shortest = await a.nsmallest(words, 2, key=len) print(shortest) # ['pie', 'fig'] # Async key function async def get_score(name): scores = {"Alice": 95, "Bob": 87, "Charlie": 92, "David": 78} return scores[name] top_students = await a.nlargest( ["Alice", "Bob", "Charlie", "David"], 2, key=get_score ) print(top_students) # ['Alice', 'Charlie'] ``` -------------------------------- ### Group into fixed-size batches Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Splits an iterable into tuples of a fixed size. The strict mode raises a ValueError if the final batch is incomplete. ```python import asyncstdlib as a async def example(): items = range(10) # Batch into groups of 3 async for batch in a.batched(items, 3): print(batch) # (0, 1, 2) # (3, 4, 5) # (6, 7, 8) # (9,) <- last batch may be smaller # Strict mode raises if last batch is incomplete try: async for batch in a.batched(items, 3, strict=True): pass except ValueError as e: print(f"Error: {e}") # batched(): incomplete batch ``` -------------------------------- ### Async cached property descriptor Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Transforms an async method into a cached property that computes its value only once and caches the result. Useful for expensive asynchronous initializations. ```python import asyncstdlib as a import asyncio class Resource: def __init__(self, url: str): self.url = url @a.cached_property async def data(self): print(f"Fetching {self.url}...") await asyncio.sleep(0.1) # Simulate network delay return {"url": self.url, "content": "example data"} async def example(): resource = Resource("https://api.example.com") # First access computes and caches data = await resource.data # Prints: Fetching https://api.example.com... print(data["content"]) # example data # Subsequent access uses cached value data = await resource.data # No fetch - cached! print(data["content"]) # example data # Delete to clear cache del resource.data # Next access recomputes data = await resource.data # Prints: Fetching... # With lock for thread-safety class SafeResource: def __init__(self, url: str): self.url = url @a.cached_property(asyncio.Lock) async def data(self): print("Fetching...") return "data" ``` -------------------------------- ### anext - Retrieve next item from async iterator Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Retrieves the next item from an async iterator, supporting an optional default value if the iterator is exhausted. ```APIDOC ## anext ### Description Retrieves the next item from an async iterator. If the iterator is exhausted, it returns the default value if provided, otherwise it raises StopAsyncIteration. ### Parameters #### Arguments - **iterator** (AsyncIterator) - Required - The async iterator to retrieve from. - **default** (Any) - Optional - Value to return if the iterator is exhausted. ``` -------------------------------- ### Unbounded async cache decorator Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Provides a simple unbounded cache for async functions, suitable for scenarios where memory usage is not a primary concern or the number of unique calls is limited. ```python import asyncstdlib as a @a.cache async def expensive_computation(x: int, y: int): print(f"Computing {x} + {y}...") return x + y async def example(): result = await expensive_computation(1, 2) # Computing 1 + 2... print(result) # 3 result = await expensive_computation(1, 2) # Cached! print(result) # 3 result = await expensive_computation(2, 3) # Computing 2 + 3... print(result) # 5 ``` -------------------------------- ### Scoping Async Iterator Lifetime with asyncstdlib.scoped_iter Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/notes/iter_scope.rst Illustrates how to use `asyncstdlib.scoped_iter` to manage the lifetime of an async iterator, allowing it to be reused within an `async with` block and ensuring it's closed upon exiting the block. ```python3 import asyncio import asyncstdlib as a async def async_squares(i=0): """Provide an infinite stream of squared numbers""" while True: await asyncio.sleep(0.1) yield i**2 i += 1 async def main(): # iterator can be re-used in the async with block async with a.scoped_iter(async_squares()) as async_iter: async for s in a.islice(async_iter, 3): print(f"1st Batch: {s}") # async_iter is still open for further iteration async for s in a.islice(async_iter, 3): print(f"2nd Batch: {s}") async for s in a.islice(async_iter, 3): print(f"3rd Batch: {s}") # iterator is closed after the async with block assert await a.anext(async_iter, "Closed!") == "Closed!" asyncio.run(main()) ``` -------------------------------- ### Iterator Management Utilities Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/asynctools.rst Functions for managing the lifetime and scope of asynchronous iterators. ```APIDOC ## borrow(iterator: async iter T) -> async iter T ### Description Borrows an asynchronous iterator, allowing it to be used while maintaining its state. ### Parameters #### Request Body - **iterator** (async iter T) - Required - The asynchronous iterator to borrow. ## scoped_iter(iterable: (async) iter T) ### Description Creates a scoped asynchronous iterator that ensures proper cleanup of the underlying iterable. ### Parameters #### Request Body - **iterable** ((async) iter T) - Required - The iterable to be scoped. ``` -------------------------------- ### Universal async iterator with any_iter Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt any_iter converts various 'async-like' iterables into a uniform async iterator. This function provides a consistent way to work with different types of asynchronous iterables, simplifying asynchronous iteration logic. ```python import asyncstdlib as a import random ``` -------------------------------- ### asyncstdlib.heapq.merge Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/heapq.rst Merges multiple sorted iterables (including async iterables) into a single sorted iterator. Supports an optional key function and reverse sorting. ```APIDOC ## asyncstdlib.heapq.merge ### Description Merges multiple sorted iterables into a single sorted iterator. Supports asynchronous iterables and an optional asynchronous key function. ### Method N/A (Function) ### Endpoint N/A (Function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A (Returns an iterator) #### Response Example N/A ``` -------------------------------- ### map - Apply function to items Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Creates an async iterator applying a function to items from one or more iterables. ```APIDOC ## map ### Description Applies a function (sync or async) to every item of an iterable and returns an async iterator of the results. ### Parameters #### Arguments - **func** (Callable) - Required - The function to apply to each item. - **iterables** (Iterable/AsyncIterable) - Required - One or more iterables to map over. ``` -------------------------------- ### Split iterator into multiple with tee Source: https://context7.com/maxfischer2781/asyncstdlib/llms.txt Creates multiple independent asynchronous iterators from a single iterable. Can be used as a context manager for safe cleanup or with a lock for concurrent access. ```python import asyncstdlib as a async def example(): numbers = [1, 2, 3, 4, 5] # Create two independent iterators iter1, iter2 = a.tee(numbers, n=2) # Each can be iterated independently result1 = await a.list(iter1) result2 = await a.list(iter2) print(result1) # [1, 2, 3, 4, 5] print(result2) # [1, 2, 3, 4, 5] # Use as context manager for safe cleanup async with a.tee(numbers, n=3) as (a1, a2, a3): first = await a.anext(a1) second = await a.anext(a2) print(first, second) # 1, 1 # For concurrent access, provide a lock import asyncio iter1, iter2 = a.tee(numbers, n=2, lock=asyncio.Lock()) ``` -------------------------------- ### Iterator Splitting Source: https://github.com/maxfischer2781/asyncstdlib/blob/master/docs/source/api/itertools.rst Functions for splitting or grouping iterators. ```APIDOC ## batched(iterable, n, strict=False) ### Description Batches an iterable into tuples of length n. ### Parameters #### Request Body - **iterable** ((async) iter T) - Required - The source iterable. - **n** (int) - Required - The size of each batch. - **strict** (bool) - Optional - If True, raises an error if the last batch is smaller than n. ```