Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async def gen() -> AsyncIterator[T]:
for item in cast(Iterable[T], itr):
yield item
return_exceptions: bool = False,
limit: int = -1
) -> List[Any]:
"""Like asyncio.gather but with a limit on concurrency.
Much of the complexity of gather comes with it support for cancel, which we
omit here. Note that all results are buffered.
"""
# For detecting input duplicates and reconciling them at the end
input_map: Dict[Awaitable[T], List[int]] = {}
# This is keyed on what we'll get back from asyncio.wait
pos: Dict[asyncio.Future[T], int] = {}
ret: List[Any] = [None] * len(args)
pending: Set[asyncio.Future[T]] = set()
done: Set[asyncio.Future[T]] = set()
next_arg = 0
while True:
while next_arg < len(args) and (limit == -1 or len(pending) < limit):
# We have to defer the creation of the Task as long as possible
# because once we do, it starts executing, regardless of what we
# have in the pending set.
if args[next_arg] in input_map:
input_map[args[next_arg]].append(next_arg)
else:
# We call ensure_future directly to ensure that we have a Task
# because the return value of asyncio.wait will be an implicit
# task otherwise, and we won't be able to know which input it
# corresponds to.
async def compress(
itr: AnyIterable[T], selectors: AnyIterable[Any]
) -> AsyncIterator[T]:
"""
Yield elements only when the corresponding selector evaluates to True.
Stops when either the iterable or the selectors have been exhausted.
Example:
async for value in compress(range(5), [1, 0, 0, 1, 1]):
... # 0, 3, 4
"""
async for value, selector in zip(itr, selectors):
if selector:
yield value
async def sum(itr: AnyIterable[T], start: T = None) -> T:
"""
Compute the sum of a mixed iterable, adding each value with the start value.
Example:
await sum(generator())
-> 1024
"""
value: T
if start is None:
value = cast(T, 0) # emulate stdlib but still type nicely for non-ints
else:
value = start
async for item in iter(itr):
value += item # type: ignore # mypy doesn't know T + T
return value