anext() Function in Python With Example

In this tutorial, we will learn about anext() function in python with example.

Getting Started

Like aiter() method, anext() function is a newly introduced function in python 3.10 which when awaited, return the next item from the given asynchronous iterator, or default if given and the iterator is exhausted.

This is the async variant of the next() builtin, and behaves similarly.

Syntax of anext() Function

Syntax of anext() function –

 
anext(async_iterator[, default])

Parameters

As shown above, anext() function takes two arguments –
1. asynchronous iterator
2. default value, which is to be returned on certain condition.

Return Type

As discussed above, anext() function –
When awaited, return the next item from the given asynchronous iterator, or default if given and the iterator is exhausted.

Examples of anext() Function

Below is an example of anext() function –

async def test_get_before_put(self):
     channel = AsyncChannel()
     get, put = await asyncio.gather(
             anext(channel),
             momentarily(1, channel.put('foo')))
     self.assertIsNone(put)
     self.assertEqual(get, 'foo')

Leart more at official doc

Leave a Reply