欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python內(nèi)置函數(shù)anext的具體使用

 更新時間:2023年01月18日 10:19:03   作者:OceanStar的學(xué)習(xí)筆記  
本文主要介紹了python內(nèi)置函數(shù)anext的具體使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

作用

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

語法

awaitable anext(async_iterator[, default])

其中 async_iterator 是一個異步迭代器。 它接受一個可選參數(shù),當(dāng)?shù)骱谋M時返回。

當(dāng)進(jìn)入 await 狀態(tài)時,從給定異步迭代器(asynchronous iterator)返回下一數(shù)據(jù)項(xiàng),迭代完畢則返回 default。

這是內(nèi)置函數(shù) next() 的異步版本,類似于調(diào)用 async_iterator 的 anext() 方法,返回一個 awaitable,等待返回迭代器的下一個值。若有給出 default,則在迭代完畢后會返回給出的值,否則會觸發(fā) 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
'''

到此這篇關(guān)于python內(nèi)置函數(shù)anext的具體使用的文章就介紹到這了,更多相關(guān)python內(nèi)置函數(shù)anext內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論