[Python] Why does this async generator/anext snippet result in SystemError: <class...

Discussão em 'Python' iniciado por Stack, Dezembro 17, 2024.

  1. Stack

    Stack Membro Participativo

    Given this simple snippet, why does the first anext() call work but the second anext() results in a strange error?

    Reading the documentation of anext(), I would assume that the supplied default would be used when there is no "next" value available:


    If default is given, it is returned if the iterator is exhausted, otherwise StopAsyncIteration is raised.
    ​

    Running this in an (interactive) Python 3.12 interpreter on MacOS Apple M3 Pro,

    import asyncio

    async def generator(it=None):
    if it is not None:
    yield (it, it)

    async def my_func():
    # results in a=1 b=1
    a, b = await anext(generator(1), (2, 3))

    # results in no printing
    async for a, b in generator():
    print(a, b)

    # raises exception
    a, b = await anext(generator(), (2, 3))

    loop = asyncio.new_event_loop()
    loop.run_until_complete(my_func())


    results in this exception:

    StopAsyncIteration

    The above exception was the direct cause of the following exception:

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/Users/manuel/.pyenv/versions/3.12.0/lib/python3.12/asyncio/base_events.py", line 664, in run_until_complete
    return future.result()
    ^^^^^^^^^^^^^^^
    File "<stdin>", line 6, in my_func
    SystemError: <class 'StopIteration'> returned a result with an exception set


    My snippet fails in Python 3.11 & 3.13 too with the same exception message.

    Continue reading...

Compartilhe esta Página