Python anext() 函式



Python anext() 函式 是一個非同步迭代器方法,允許我們從非同步迭代器中檢索下一個專案。此處,非同步迭代器的定義是指實現了 __aiter__()__anext__() 方法的物件。anext() 函式是在 3.10 版本中引入的,作為非同步程式設計功能。

在同步迭代中,程式會阻塞或等待每個操作完成,然後才能繼續執行下一個操作。但是,使用非同步的 anext() 函式,程式可以啟動另一個操作,而無需等待前一個操作完成。

語法

以下是 Python anext() 函式的語法:

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

引數

Python anext() 函式接受一個或兩個引數:

  • asyncIterator - 表示一個非同步可迭代物件。

  • default - 指示預設值。

返回值

Python anext() 函式返回指定非同步迭代器的下一個元素。

示例

讓我們透過一些示例來了解 anext() 函式是如何工作的:

示例 1

以下示例演示了 Python anext() 函式的使用。這裡我們建立一個非同步空列表物件,並嘗試使用 anext() 函式列印其第一個元素。由於列表為空,因此將顯示預設值。

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())

當我們執行以上程式時,它會產生以下結果:

The first element of the list: None

示例 2

在下面的程式碼中,我們將使用 anext() 函式列印指定數字範圍內的第一個元素。

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())

以下是以上程式碼的輸出:

The first element is: 1

示例 3

下面的程式碼演示瞭如何在 Python 中使用 anext() 函式從指定範圍內找到第一個偶數。首先,將建立一個非同步方法來查詢前 10 個偶數。然後,我們呼叫 anext() 函式來列印結果。

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())

以上程式碼的輸出如下:

The first even number: 2
python_built_in_functions.htm
廣告