mode.utils.aiter
Async iterator utilities: aiter, anext, etc.
Python gained aiter() and anext() as builtins in 3.10, long after this
module was written. The versions here are kept because they are not the
same functions:
aiteralso accepts a synchronous iterable, wrapping it so that it can be driven withasync for. The builtin raisesTypeErrorfor anything that does not implement__aiter__.anexttakes its default as*defaultrather than as a single positional argument.
Both names shadow the builtins for the rest of this module, so aiter
below always means the dispatcher defined here.
AsyncIterWrapper
Bases: AsyncIterator[T]
Wrap regular Iterator into an AsyncIterator.
Source code in mode/utils/aiter.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | |
arange
Bases: AsyncIterable[int]
Async generator that counts like range.
Source code in mode/utils/aiter.py
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
aenumerate(it, start=0)
async
async for version of enumerate.
Source code in mode/utils/aiter.py
36 37 38 39 40 41 42 43 | |
aiter(it)
Create an async iterator from an async or synchronous iterable.
Unlike the aiter builtin added in Python 3.10, a synchronous
iterable is accepted as well: it is wrapped in AsyncIterWrapper so
that it can be consumed with async for.
>>> [x async for x in aiter([1, 2, 3])]
[1, 2, 3]
Raises:
| Type | Description |
|---|---|
TypeError
|
if the argument is neither an |
Notes
If the object is already an iterator, the iterator
should return self when __aiter__ is called.
Source code in mode/utils/aiter.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
alist(ait)
async
Convert async generator to list.
Source code in mode/utils/aiter.py
162 163 164 | |
anext(it, *default)
async
Get next value from async iterator, or default if empty.
Differs from the anext builtin added in Python 3.10: the default is
taken as *default, so passing no default and passing one are both
handled by this single signature.
Raises:
| Type | Description |
|---|---|
|
exc: |
Source code in mode/utils/aiter.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | |
aslice(ait, *slice_args)
async
Extract slice from async generator.
Source code in mode/utils/aiter.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | |
chunks(it, n)
async
Split an async iterator into chunks with n elements each.
Example:
# n == 2
>>> x = chunks(arange(10), 2)
>>> [item async for item in x]
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10]]
# n == 3
>>> x = chunks(arange(10)), 3)
>>> [item async for item in x]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]
Source code in mode/utils/aiter.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | |