Introduction
anext()
is a new function that came in Python 3.10 version. It returns the next item from an asynchronous iterator when awaited, or default if given and the iterator is exhausted. This is the async variant of the next()
built-in and behaves similarly. We'll discuss next()
in a later part.
The syntax of the anext()
function looks like this:
anext(async_iterator[, default])
where async_iterator
is an asynchronous iterator. It takes an optional parameter, which is returned when the iterator is exhausted.
Examples
If you remember in the part where we had discussed aiter()
function, we had seen an example. We'll use a similar example here too.
To create a real async comprehension, we will need to call another async def
function. Let's see an example:
import asyncio
async def numbers(num):
for i in range(num):
yield i
await asyncio.sleep(0.5)
async def check_odd(num):
it = aiter(numbers(num))
while True:
x = await anext(it)
if x % 2 != 0:
print(f"{x} is Odd!!")
if __name__ == " __main__":
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(check_odd(10))
finally:
event_loop.close()
When you run this code, you'll get this output:
1 is Odd!!
3 is Odd!!
5 is Odd!!
7 is Odd!!
9 is Odd!!
Traceback (most recent call last):
File "C:\Users\ashut\Desktop\Test\Blog-Codes\Built-Ins\anext\main.py", line 30, in <module>
event_loop.run_until_complete(check_odd(10))
File "C:\Users\ashut\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 641, in run_until_complete
return future.result()
File "C:\Users\ashut\Desktop\Test\Blog-Codes\Built-Ins\anext\main.py", line 12, in check_odd
x = await anext(it)
StopAsyncIteration
In the above code, the numbers()
function is an asynchronous generator that is yielding values. Further, we have defined another async function check_odd()
that uses the aiter()
function to create an asynchronous iterator. Then anext()
function is used to get the next value from this asynchronous iterator. But if you see the output we encounter an error once we reach the end of the list. We can remove this error if we use the optional parameter.
import asyncio
async def numbers(num):
for i in range(num):
yield i
await asyncio.sleep(0.5)
async def check_odd(num):
it = aiter(numbers(num))
while True:
x = await anext(it, 'end')
if x == 'end':
break
elif x % 2 != 0:
print(f"{x} is Odd!!")
if __name__ == " __main__":
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(check_odd(10))
finally:
event_loop.close()
When you run this code, you'll get this output:
1 is Odd!!
3 is Odd!!
5 is Odd!!
7 is Odd!!
9 is Odd!!
In the above code, we have added another parameter 'end' to the anext()
function. Once it returns 'end', we break the loop and hence we don't encounter any error this time.
Conclusion
This was a brief introduction to anext()
in Python. You can find more examples here.