iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python内置函数anext的具体使用
  • 583
分享到

python内置函数anext的具体使用

python内置函数anextpythonanext 2023-01-18 12:01:33 583人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

作用 anext() 是 python 3.10 版本中的一个新函数。它在等待时从异步迭代器返回下一项,如果给定并且迭代器已用尽,则返回默认值。这是 next() 内置的异步变体,行

作用

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
'''

到此这篇关于Python内置函数anext的具体使用的文章就介绍到这了,更多相关python内置函数anext内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: python内置函数anext的具体使用

本文链接: https://www.lsjlt.com/news/178077.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作