This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: why save the item to be replaced as olditem in PyTuple_SetItem? It's not useful at all.
Type: performance Stage: resolved
Components: Devguide Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: ezio.melotti, maliubiao@gmail.com, pitrou
Priority: normal Keywords:

Created on 2014-03-16 15:08 by maliubiao@gmail.com, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg213730 - (view) Author: coder.maliubiao (maliubiao@gmail.com) Date: 2014-03-16 15:08
code:
int
PyTuple_SetItem(register PyObject *op, register Py_ssize_t i, PyObject *newitem)
{
    register PyObject *olditem;
    register PyObject **p;
    if (!PyTuple_Check(op) || op->ob_refcnt != 1) {
        Py_XDECREF(newitem);
        PyErr_BadInternalCall();
        return -1;
    }
    if (i < 0 || i >= Py_SIZE(op)) {
        Py_XDECREF(newitem);
        PyErr_SetString(PyExc_IndexError,
                        "tuple assignment index out of range");
        return -1;
    }
    p = ((PyTupleObject *)op) -> ob_item + i;
    olditem = *p;
    *p = newitem;
    Py_XDECREF(olditem);
    return 0;
}

olditem is not useful.
msg213739 - (view) Author: Antoine Pitrou (pitrou) * (Python committer) Date: 2014-03-16 17:15
> olditem is not useful

It is. Py_XDECREF() may have massive side effects (such as calling a __del__ method and executing arbitrary code). Therefore, you have to ensure that the tuple item is set to the new value *before* the old value is DECREF'ed. Otherwise, any code invoked by Py_XDECREF will see invalid tuple contents, and the interpreter may crash.
History
Date User Action Args
2022-04-11 14:58:00adminsetgithub: 65144
2014-06-19 22:56:38ezio.melottisetstage: resolved
2014-03-16 20:46:45benjamin.petersonsetstatus: open -> closed
resolution: not a bug
2014-03-16 17:15:22pitrousetnosy: + pitrou
messages: + msg213739
2014-03-16 15:11:10maliubiao@gmail.comsettype: performance
2014-03-16 15:08:05maliubiao@gmail.comcreate