日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python內置函數anext的具體使用_python

作者:OceanStar的學習筆記 ? 更新時間: 2023-03-16 編程語言

作用

anext() 是 Python 3.10 版本中的一個新函數。它在等待時從異步迭代器返回下一項,如果給定并且迭代器已用盡,則返回默認值。這是 next() 內置的異步變體,行為類似。

語法

awaitable anext(async_iterator[, default])

其中 async_iterator 是一個異步迭代器。 它接受一個可選參數,當迭代器耗盡時返回。

當進入 await 狀態時,從給定異步迭代器(asynchronous iterator)返回下一數據項,迭代完畢則返回 default。

這是內置函數 next() 的異步版本,類似于調用 async_iterator 的 anext() 方法,返回一個 awaitable,等待返回迭代器的下一個值。若有給出 default,則在迭代完畢后會返回給出的值,否則會觸發 StopAsyncIteration。

例子

import asyncio

class CustomAsyncIter:
? ? def __init__(self):
? ? ? ? self.iterator = iter(['A', 'B'])
? ? def __aiter__(self):
? ? ? ? return self
? ? async def __anext__(self):
? ? ? ? try:
? ? ? ? ? ? x = next(self.iterator)
? ? ? ? except StopIteration:
? ? ? ? ? ? raise StopAsyncIteration from None
? ? ? ? await asyncio.sleep(1)
? ? ? ? return x

async def main1():
? ? iter1 = CustomAsyncIter()
? ? print(await anext(iter1)) ? ? ? # Prints 'A'
? ? print(await anext(iter1)) ? ? ? # Prints 'B'
? ? print(await anext(iter1)) ? ? ? # Raises StopAsyncIteration

async def main2():
? ? iter1 = CustomAsyncIter()
? ? print('Before') ? ? ? ? ? ? ? ? # Prints 'Before'
? ? print(await anext(iter1, 'Z')) ?# Silently terminates the script!!!
? ? print('After') ? ? ? ? ? ? ? ? ?# This never gets executed

asyncio.run(main1())
'''
A
B
raise StopAsyncIteration
'''

asyncio.run(main2())
'''
Before
A
After
'''

原文鏈接:https://blog.csdn.net/zhizhengguan/article/details/128562537

欄目分類
最近更新