This is a little complicated by the lack of a functionaiter() in Python 3.6 (it will be added in 3.7 after the return expected from being __aiter__properly deprecated). There are no asynchronous versions of objects yet itertools.
Define your own:
try:
aiter
except NameError:
from inspect import iscoroutinefunction as _isasync
def aiter(ob, _isasync=_isasync):
obtype = type(ob)
if not hasattr(obtype, '__aiter__'):
raise TypeError(f'{obtype.__name__!r} object is not async iterable')
async_iter = obtype.__aiter__(ob)
if _isasync(async_iter):
raise TypeError(f'{obtype.__name__!r} object is not async iterable')
return async_iter
del _isasync
async islice chain:
class achain():
"""Chain over multiple async iterators"""
def __init__(self, *async_iterables):
self._source = iter(async_iterables)
self._active = None
def __aiter__(self):
return self
async def __anext__(self):
if self._source is None:
raise StopAsyncIteration
if self._active is None:
ait = next(self._source, None)
if ait is None:
self._source = None
raise StopAsyncIteration
self._active = aiter(ait)
try:
return await type(ait).__anext__(ait)
except StopAsyncIteration:
self._active = None
return await self.__anext__()
class aslice():
"""Slice an async iterator"""
def __init__(self, ait, start, stop=None, step=1):
if stop is None:
start, stop = 0, start
self._ait = ait
self._next, self._stop, self._step = start, stop, step
self._cnt = 0
def __aiter__(self):
return self
async def __anext__(self):
ait, stop = self._ait, self._stop
if ait is None:
raise StopAsyncIteration
anext = type(ait).__anext__
while self._cnt < self._next:
try:
await anext(ait)
except StopAsyncIteration:
self._ait = None
raise
self._cnt += 1
if stop is not None and self._cnt >= stop:
self._ait = None
raise StopAsyncIteration
try:
item = await anext(ait)
except StopAsyncIteration:
self._ait = None
raise
self._cnt += 1
self._next += self._step
return item
async :
async def get_chunks_it(l, n):
""" Chunks an async iterator `l` in size `n`
Args:
l (Iterator[Any]): an iterator
n (int): size of
Returns:
Generator[Any]
"""
iterator = aiter(l)
async for first in iterator:
async def afirst():
yield first
yield achain(afirst, aslice(iterator, n - 1))