Python anext() Function



The Python anext() function is an asynchronous iterator method that allows us to retrieve the next item from an asynchronous iterator. Here, The term asynchronous iterator is defined as an object that implements the __aiter__() and __anext__() methods. The anext() function was introduced in version 3.10 as an asynchronous programming feature.

In synchronous iteration, the program block or wait for each operation to complete before moving on to the next one. However, with anext() function which is asynchronous in nature, the program is allowed to initiate another operation without waiting for the previous ones to finish.

Syntax

Following is the syntax of the Python anext() function −

awaitable anext(asyncIterator)
or
awaitable anext(asyncIterator, default)

Parameters

The Python anext() function accepts either or both parameters −

  • asyncIterator − It represents an asynchronous iterable object.

  • default − It indicates the default value.

Return Value

The Python anext() function returns next element from the specified asynchronous iterator.

Examples

Let's understand how anext() function works with the help of some examples −

Example 1

The following example shows the usage of Python anext() function. Here we are creating an asynchronous empty list object and trying to print its first element using anext() function. Since the list is empty, the default value will be displayed.

import asyncio
class AsyncIterator:
   def __init__(self, data):
      self.data = data
      self.index = 0

   def __aiter__(self):
      return self

   async def __anext__(self):
      if self.index == len(self.data):
         raise StopAsyncIteration
      value = self.data[self.index]
      return value

async def main():
   async_iter = AsyncIterator([])
   first_even = await anext(async_iter, None)
   print("The first element of the list:", first_even)
        
asyncio.run(main())

When we run above program, it produces following result −

The first element of the list: None

Example 2

In the code below, we are going to print the first element from the specified range of numbers using the anext() function.

import asyncio
async def async_gen_example():
   async def async_gen():
      for i in range(1, 3):
         yield i
   gen = async_gen()
   first_item = await anext(gen)
   print("The first element is:", first_item)

if __name__ == "__main__":
   asyncio.run(async_gen_example())

Following is an output of the above code −

The first element is: 1

Example 3

The code below demonstrates how to find the first even number from the specified range with the help of anext() function in Python. First, an asynchronous method will be created to find the first 10 even numbers. Then, we call the anext() function to print the result.

import asyncio
async def async_gen_example():
   async def even_async_gen():
      i = 1
      num = 0
      while num < 10:
         if i % 2 == 0:
            num += 1
            yield i
         i += 1
       
   gen = even_async_gen()
   first_even = await anext(gen, None)
   print("The first even number:", first_even)

if __name__ == "__main__":
   asyncio.run(async_gen_example())

Output of the above code is as follows −

The first even number: 2
python_built_in_functions.htm
Advertisements