在迭代期间更改python序列大小

2024-09-28 22:21:35 发布

您现在位置:Python中文网/ 问答频道 /正文

实现的bytes.join方法的实现here包括在迭代期间防止大小更改的代码:

    if (seqlen != PySequence_Fast_GET_SIZE(seq)) {
        PyErr_SetString(PyExc_RuntimeError,
                        "sequence changed size during iteration");
        goto error;
    }

如何在bytes.join调用中修改iterable序列?为什么需要上面的代码?或者也许它不是必要的和多余的?在


Tags: 方法代码sizegetifbyteshereseq
1条回答
网友
1楼 · 发布于 2024-09-28 22:21:35

如果向bytes.join()传入一个列表对象,则在bytes.join()调用迭代时,可能会在另一个线程中将元素添加到列表中。在

计算第二个对象的总长度。在迭代时改变项目的数量会给计算带来麻烦。在

通常不能对列表执行此操作,因为GIL没有发布,但是如果列表中的任何对象是notbytes对象,则使用{a1}。作为a comment on the original patch states

The problem with your approach is that the sequence could be mutated while another thread is running (_getbuffer() may release the GIL). Then the pre-computed size gets wrong.

相关问题 更多 >