Introduce the two-argument form of `iter` to `aiter`

The builtin iter function has an overload that takes a callable and a sentinel, and extracts the return value of the callable invoked with no arguments until it equals the sentinel. It should not be difficult to make aiter support this, taking analogously a coroutine function (or more generally a function that returns an awaitable, though that cannot be reliably checked to fail early) and a sentinel and returning an async iterator.

Do you have a use case for this? My impression is two-argument iter is a legacy feature that is now rarely used.

5 Likes

I suggested this idea purely because I would expect the two to be analogs, but if I were to think of a use case, maybe asynchronous I/O where a reader would return an empty bytestring to signal EOF?

I’ve definitely looked for it and being a bit surprised it didn’t exist once or twice at least.

Not critical as most modern libraries ensure they have real iterators available as interface and but it comes up now and then when wrapping some bindings.

I would say writing new interfaces that requires it use should be deprecated in favour of real iterators but it’s a neat and useful utility for doing that conversion.

Still not that many and straightforward to replace with a while loop in most cases but it can definitely make code a bit more concise if you need it as an expression in a comprehension or such.

I’m +1 since it maps cleanly to the sync case and there are cases it’s useful and makes things clearer. Still only a convenience for quite few cases with simple workaround so not caring that much.

1 Like