Why does this async generator/anext snippet result in SystemError: returned with exception set?

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.

1

This is a Python bug, and should be reported.


When the anext-with-default-value implementation hits StopAsyncIteration, it calls _PyGen_SetStopIterationValue to replace the exception with a StopIteration. I’m not quite sure whether this is happening in __next__ or send, but both methods do essentially the same thing in this case. Here’s __next__‘s handling:

    if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)) {
        _PyGen_SetStopIterationValue(obj->default_value);
    }

_PyGen_SetStopIterationValue looks like this:

int
_PyGen_SetStopIterationValue(PyObject *value)
{
    PyObject *e;

    if (value == NULL ||
        (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
    {
        /* Delay exception instantiation if we can */
        PyErr_SetObject(PyExc_StopIteration, value);
        return 0;
    }
    /* Construct an exception instance manually with
     * PyObject_CallOneArg and pass it to PyErr_SetObject.
     *
     * We do this to handle a situation when "value" is a tuple, in which
     * case PyErr_SetObject would set the value of StopIteration to
     * the first element of the tuple.
     *
     * (See PyErr_SetObject/_PyErr_CreateException code for details.)
     */
    e = PyObject_CallOneArg(PyExc_StopIteration, value);
    if (e == NULL) {
        return -1;
    }
    PyErr_SetObject(PyExc_StopIteration, e);
    Py_DECREF(e);
    return 0;
}

This function needs to perform special handling when the argument is a tuple or an exception object. In your case, the argument is a tuple (2, 3). But the special handling has an issue.

There is already an active exception set, the StopAsyncIteration. It is not safe to call arbitrary Python APIs with an exception set. All the calls in the usual-case handling are okay, but this line in the special-case handling:

e = PyObject_CallOneArg(PyExc_StopIteration, value);

is unsafe. Python detects an inconsistent state, resulting in the error you see.

To fix this issue, either _PyGen_SetStopIterationValue or the code that calls it should use PyErr_Clear to cancel the current exception before the PyObject_CallOneArg(PyExc_StopIteration, value) call happens.

2

i solved the issue by replacing the tuple in the default parameter with a list, so [2,3] in stead of (2,3).
i cannot tell you why it doesn’t work with a tuple, but this works for me.

a, b = await anext(generator(), [2, 3])

4

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật