Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
Yield the running accumulation of an iterable and operator.
Accepts both a standard function or a coroutine for accumulation.
Example:
data = [1, 2, 3, 4]
async def mul(a, b):
return a * b
async for total in accumulate(data, func=mul):
... # 1, 2, 6, 24
"""
itr = iter(itr)
try:
total: T = await next(itr)
except AnyStop:
return
yield total
async for item in itr:
total = await maybe_await(func(total, item))
yield total
Example:
data = ["A", "a", "b", "c", "C", "c"]
async for key, group in groupby(data, key=str.lower):
key # "a", "b", "c"
group # ["A", "a"], ["b"], ["c", "C", "c"]
"""
if key is None:
key = lambda x: x
grouping: List[T] = []
it = iter(itr)
item = await next(it)
grouping = [item]
j = await maybe_await(key(item))
async for item in it:
k = await maybe_await(key(item))
if k != j:
yield j, grouping
grouping = [item]
else:
grouping.append(item)
j = k
yield j, grouping
) -> AsyncIterator[T]:
"""
Yield items from the iterable only when the predicate evaluates to False.
Accepts both standard functions and coroutines for the predicate.
Example:
def pred(x):
return x < 4
async for item in filterfalse(pred, range(6)):
... # 4, 5
"""
async for item in iter(iterable):
if not await maybe_await(predicate(item)):
yield item
) -> AsyncIterator[T]:
"""
Drops all items until the predicate evaluates False; yields all items afterwards.
Accepts both standard functions and coroutines for the predicate.
Example:
def pred(x):
return x < 4
async for item in dropwhile(pred, range(6)):
... # 4, 5, 6
"""
itr = iter(iterable)
async for item in itr:
if not await maybe_await(predicate(item)):
yield item
break
async for item in itr:
yield item
async def from_iterable(self, itrs: AnyIterableIterable[T]) -> AsyncIterator[T]:
"""
Like chain, but takes an iterable of iterables.
Alias for chain(*itrs)
"""
async for itr in iter(itrs):
async for item in iter(itr):
yield item
async def gen(k: int, q: asyncio.Queue) -> AsyncIterator[T]:
if k == 0:
async for value in iter(itr):
await asyncio.gather(*[queue.put(value) for queue in queues[1:]])
yield value
await asyncio.gather(*[queue.put(sentinel) for queue in queues[1:]])
else:
while True:
value = await q.get()
if value is sentinel:
break
yield value
async def cycle(itr: AnyIterable[T]) -> AsyncIterator[T]:
"""
Yield a repeating series from the given iterable.
Lazily consumes the iterable when the next value is needed, and caching
the values in memory for future iterations of the series.
Example:
async for value in cycle([1, 2]):
... # 1, 2, 1, 2, 1, 2, ...
"""
items = []
async for item in iter(itr):
yield item
items.append(item)
while True:
for item in items:
yield item
async def from_iterable(self, itrs: AnyIterableIterable[T]) -> AsyncIterator[T]:
"""
Like chain, but takes an iterable of iterables.
Alias for chain(*itrs)
"""
async for itr in iter(itrs):
async for item in iter(itr):
yield item