【十四】anext()函数(1) - py3

发布时间 2023-06-01 20:35:53作者: Chimengmeng

【十四】anext()函数(1) - py3.10+

【1】作用

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

【2】语法

awaitable anext(async_iterator[, default])
  • 其中 async_iterator 是一个异步迭代器。
    • 它接受一个可选参数,当迭代器耗尽时返回。
  • 当进入 await 状态时
    • 从给定异步迭代器(asynchronous iterator)返回下一数据项
    • 迭代完毕则返回 default。
  • 这是内置函数 next() 的异步版本,类似于调用 async_iterator 的 anext() 方法,返回一个 awaitable,等待返回迭代器的下一个值。
    • 若有给出 default
      • 则在迭代完毕后会返回给出的值
      • 否则会触发 StopAsyncIteration。

【3】示例

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