Is the empty tuple in Python a “constant” [duplicate]

懵懂的女人 提交于 2019-12-02 03:47:50

In CPython, the empty tuple is a singleton. Only one copy is created, ever, then reused whenever you use () or use tuple() on an empty generator.

The PyTuple_new() function essentially does this:

if (size == 0 && free_list[0]) {
    op = free_list[0];
    Py_INCREF(op);
    // ...
    return (PyObject *) op;
}

So if the tuple size is 0 (empty) and free_list[0] object exists (the existing empty tuple singleton), just use that.

See How is tuple implemented in CPython? for more details on free_list; CPython will also re-use already-created tuple instances up to length 20.

This is an implementation detail. Other implementations (Jython, IronPython, PyPy) do not have to do the same.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!