async enumeration - possible?

Ian Kelly ian.g.kelly at gmail.com
Tue Nov 29 11:19:27 EST 2016


On Tue, Nov 29, 2016 at 7:25 AM, Frank Millman <frank at chagford.com> wrote:
> However, it does not allow you to enumerate over the generator output -
>
>>>> async def main():
>
> ...   c = counter(5)
> ...   async for j, k in enumerate(c):
> ...     print(j, k)
> ...   print('done')
> ...
>>>>
>>>> loop.run_until_complete(main())
>
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
>  File
> "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\asyncio\base_events.py",
> line 466, in run_until_complete
>    return future.result()
> TypeError: 'async_generator' object is not iterable
>>>>
>>>>
>
> Is there any technical reason for this, or is it just that no-one has got
> around to writing an asynchronous version yet?

No one has written an async enumerate afaik. You may be interested in
the aitertools package in PyPI:

https://pypi.python.org/pypi/aitertools/0.1.0

It also doesn't have an async enumerate. It does have an aiter
function that can wrap an ordinary iterable into an async iterable, so
one way to write that would be aiter(enumerate(c)), with the caveat
that the wrapped iterator is still running synchronously.

Otherwise, you can write one yourself. This doesn't support all the
features of enumerate, but it serves as demonstration:

    from itertools import count

    async def aenumerate(aiterable):
        counter = count()
        async for x in aiterable:
             yield next(counter), x



More information about the Python-list mailing list