Discussion forum for David Beazley

Replacing Infinite while Loops with an Iterator: async edition


I first learned the for chunk in iter(lambda: s.recv(CHUNKSIZE), b'') trick from page 138 of the Python Cookbook (“4.16. Replacing Infinite while Loops with an Iterator”), and never looked back.

When I started to play with Curio and consuming sockets asynchronously, it occurred to me that it would be nice if we could write something like async for chunk in aiter(lambda: s.recv(CHUNKSIZE), b''), but as far as I know, we can’t. Is that right? If so, is anyone working on adding that to Python?

/cc @dave


I have no idea offhand. Seems like it would be an interesting idea though.


I started a discussion in python-ideas in case anyone is interested: