網站首頁 編程語言 正文
作用
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
相關推薦
- 2022-07-14 python?numpy.ndarray中如何將數據轉為int型_python
- 2022-05-16 .Net?MVC將Controller數據傳遞到View_實用技巧
- 2021-12-03 Android消息機制Handler深入理解_Android
- 2022-08-07 pandas中pd.groupby()的用法詳解_python
- 2022-03-27 Android?Studio實現井字游戲_Android
- 2022-03-30 C語言關鍵字之auto?register詳解_C 語言
- 2022-11-29 redis配置文件詳解
- 2021-12-21 Number的常見使用方法
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支