0
# asyncstdlib
1
2
The missing async toolbox that provides async-compatible versions of Python standard library functions and classes. It offers async implementations for builtins, itertools, functools, contextlib, and heapq modules, plus custom utilities for working with async iterables safely.
3
4
## Package Information
5
6
- **Package Name**: asyncstdlib
7
- **Language**: Python
8
- **Installation**: `pip install asyncstdlib`
9
- **Python Support**: 3.8+
10
- **Dependencies**: Zero runtime dependencies
11
12
## Core Imports
13
14
```python
15
import asyncstdlib
16
```
17
18
Most commonly, import specific functions directly:
19
20
```python
21
from asyncstdlib import zip, map, filter, enumerate, all, any
22
from asyncstdlib import reduce, lru_cache
23
from asyncstdlib import contextmanager, closing
24
from asyncstdlib import chain, accumulate
25
from asyncstdlib import borrow, scoped_iter
26
```
27
28
## Basic Usage
29
30
```python
31
import asyncstdlib
32
33
async def example():
34
# Async versions of built-in functions
35
async_iter = asyncstdlib.map(lambda x: x * 2, [1, 2, 3, 4, 5])
36
doubled_values = await asyncstdlib.list(async_iter)
37
print(doubled_values) # [2, 4, 6, 8, 10]
38
39
# Works with any async iterable
40
async def async_generator():
41
for i in range(5):
42
yield i
43
44
result = await asyncstdlib.sum(async_generator())
45
print(result) # 10
46
47
# Safe async iteration
48
async with asyncstdlib.scoped_iter(async_generator()) as scoped:
49
async for value in scoped:
50
print(value)
51
if value >= 2:
52
break
53
# Automatically cleaned up, no StopAsyncIteration leaks
54
55
# Run the example
56
import asyncio
57
asyncio.run(example())
58
```
59
60
## Architecture
61
62
asyncstdlib is designed around the principle of **async neutrality** - it works seamlessly with any async event loop (asyncio, trio, or custom implementations) without favoring specific frameworks. The library maintains the exact same API signatures as the standard library counterparts while providing async-compatible behavior.
63
64
Key design principles:
65
- **Drop-in replacements**: Same function signatures as standard library equivalents
66
- **Safe iteration**: Proper cleanup of async iterators to prevent resource leaks
67
- **Type safety**: Complete type annotations and stub files for full typing support
68
- **Performance**: Optimized implementations designed specifically for async contexts
69
70
## Capabilities
71
72
### Built-in Functions
73
74
Async versions of Python's built-in functions for iteration, aggregation, and data processing. These provide the fundamental async building blocks that mirror Python's standard builtins.
75
76
```python { .api }
77
async def anext(iterator, default=...): ...
78
def zip(*iterables, strict=False): ...
79
def map(function, *iterables): ...
80
def filter(function, iterable): ...
81
def enumerate(iterable, start=0): ...
82
def iter(subject, sentinel=None): ...
83
async def all(iterable): ...
84
async def any(iterable): ...
85
async def max(iterable, key=None, default=...): ...
86
async def min(iterable, key=None, default=...): ...
87
async def sum(iterable, start=0): ...
88
async def list(iterable=()): ...
89
async def dict(iterable=(), **kwargs): ...
90
async def set(iterable=()): ...
91
async def tuple(iterable=()): ...
92
async def sorted(iterable, key=None, reverse=False): ...
93
```
94
95
[Built-in Functions](./builtins.md)
96
97
### Iteration Tools
98
99
Async versions of itertools functions providing powerful iteration patterns including infinite iterators, filtering, grouping, and combinatorial functions.
100
101
```python { .api }
102
def accumulate(iterable, function=None, initial=None): ...
103
def batched(iterable, n, strict=False): ...
104
def cycle(iterable): ...
105
def chain(*iterables): ...
106
def compress(data, selectors): ...
107
def dropwhile(predicate, iterable): ...
108
def filterfalse(predicate, iterable): ...
109
def islice(iterable, start, stop=None, step=None): ...
110
def takewhile(predicate, iterable): ...
111
def starmap(function, iterable): ...
112
def tee(iterable, n=2, lock=None): ...
113
def pairwise(iterable): ...
114
def zip_longest(*iterables, fillvalue=None): ...
115
def groupby(iterable, key=None): ...
116
```
117
118
[Iteration Tools](./itertools.md)
119
120
### Functional Programming
121
122
Async versions of functools utilities including reduction, caching, and property decorators designed for async functions and methods.
123
124
```python { .api }
125
async def reduce(function, iterable, initial=None): ...
126
def lru_cache(maxsize=128, typed=False): ...
127
def cache(user_function): ...
128
def cached_property(getter): ...
129
```
130
131
[Functional Programming](./functools.md)
132
133
### Context Management
134
135
Async context managers and decorators for resource management, providing async versions of contextlib utilities with additional safety features.
136
137
```python { .api }
138
def contextmanager(func): ...
139
class ContextDecorator: ...
140
class closing: ...
141
class nullcontext: ...
142
class ExitStack: ...
143
```
144
145
[Context Management](./contextlib.md)
146
147
### Heap Operations
148
149
Async versions of heapq functions for working with priority queues and sorted data structures in async contexts.
150
151
```python { .api }
152
def merge(*iterables, key=None, reverse=False): ...
153
async def nlargest(iterable, n, key=None): ...
154
async def nsmallest(iterable, n, key=None): ...
155
```
156
157
[Heap Operations](./heapq.md)
158
159
### Async Utilities
160
161
Custom utilities specific to asyncstdlib for safely working with async iterables, borrowing iterators, scoped iteration, and bridging sync/async contexts.
162
163
```python { .api }
164
def borrow(iterable): ...
165
def scoped_iter(iterable): ...
166
async def await_each(awaitables): ...
167
def any_iter(*iterables): ...
168
async def apply(function, *args, **kwargs): ...
169
def sync(async_function, *args, **kwargs): ...
170
```
171
172
[Async Utilities](./asynctools.md)
173
174
## Types
175
176
Core types used throughout the asyncstdlib API:
177
178
```python { .api }
179
# Type variables
180
T = TypeVar('T') # Generic type
181
T1 = TypeVar('T1') # Generic type variants
182
T2 = TypeVar('T2')
183
T3 = TypeVar('T3')
184
T4 = TypeVar('T4')
185
T5 = TypeVar('T5')
186
R = TypeVar('R') # Return type
187
LT = TypeVar('LT') # Less-than comparable type
188
HK = TypeVar('HK', bound=Hashable) # Hashable key type
189
ADD = TypeVar('ADD') # Addable type
190
S = TypeVar('S') # Send type for generators
191
192
# Type aliases for any iterable (sync or async)
193
AnyIterable = Union[Iterable[T], AsyncIterable[T]]
194
195
# Async iterator that can be closed
196
class AsyncIterator(Protocol[T]):
197
async def __anext__(self) -> T: ...
198
async def aclose(self) -> None: ...
199
200
# Async generator protocol
201
class AsyncGenerator(AsyncIterator[T], Generic[T, S]):
202
async def asend(self, value: S) -> T: ...
203
async def athrow(self, typ: type, val: Any = None, tb: Any = None) -> T: ...
204
205
# Context manager protocols
206
class AsyncContextManager(Protocol[T]):
207
async def __aenter__(self) -> T: ...
208
async def __aexit__(self, exc_type, exc_val, exc_tb) -> Optional[bool]: ...
209
210
# Type guard protocol
211
class TypeGuard(Protocol):
212
def __call__(self, obj: Any) -> bool: ...
213
```