python:内置函数anext

作用

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值