bpo-40429: Refactor super_init() (GH-19776)

Add super_init_without_args() sub-function. Hold a strong reference
to the frame code object while calling super_init_without_args().
This commit is contained in:
Victor Stinner 2020-04-29 02:28:23 +02:00 committed by GitHub
parent f7bbf58aa9
commit cc0dc7e484
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -8015,37 +8015,17 @@ super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
}
static int
super_init(PyObject *self, PyObject *args, PyObject *kwds)
super_init_without_args(PyFrameObject *f, PyCodeObject *co,
PyTypeObject **type_p, PyObject **obj_p)
{
superobject *su = (superobject *)self;
PyTypeObject *type = NULL;
PyObject *obj = NULL;
PyTypeObject *obj_type = NULL;
if (!_PyArg_NoKeywords("super", kwds))
return -1;
if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
return -1;
if (type == NULL) {
/* Call super(), without args -- fill in from __class__
and first local variable on the stack. */
PyFrameObject *f;
Py_ssize_t i, n;
f = PyThreadState_GetFrame(_PyThreadState_GET());
if (f == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"super(): no current frame");
return -1;
}
PyCodeObject *co = PyFrame_GetCode(f);
Py_DECREF(co); // use a borrowed reference
if (co->co_argcount == 0) {
PyErr_SetString(PyExc_RuntimeError,
"super(): no arguments");
return -1;
}
obj = f->f_localsplus[0];
PyObject *obj = f->f_localsplus[0];
Py_ssize_t i, n;
if (obj == NULL && co->co_cell2arg) {
/* The first argument might be a cell. */
n = PyTuple_GET_SIZE(co->co_cellvars);
@ -8063,12 +8043,16 @@ super_init(PyObject *self, PyObject *args, PyObject *kwds)
"super(): arg[0] deleted");
return -1;
}
if (co->co_freevars == NULL)
if (co->co_freevars == NULL) {
n = 0;
}
else {
assert(PyTuple_Check(co->co_freevars));
n = PyTuple_GET_SIZE(co->co_freevars);
}
PyTypeObject *type = NULL;
for (i = 0; i < n; i++) {
PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
assert(PyUnicode_Check(name));
@ -8101,6 +8085,43 @@ super_init(PyObject *self, PyObject *args, PyObject *kwds)
"super(): __class__ cell not found");
return -1;
}
*type_p = type;
*obj_p = obj;
return 0;
}
static int
super_init(PyObject *self, PyObject *args, PyObject *kwds)
{
superobject *su = (superobject *)self;
PyTypeObject *type = NULL;
PyObject *obj = NULL;
PyTypeObject *obj_type = NULL;
if (!_PyArg_NoKeywords("super", kwds))
return -1;
if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj))
return -1;
if (type == NULL) {
/* Call super(), without args -- fill in from __class__
and first local variable on the stack. */
PyThreadState *tstate = _PyThreadState_GET();
PyFrameObject *f = PyThreadState_GetFrame(tstate);
if (f == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"super(): no current frame");
return -1;
}
PyCodeObject *code = PyFrame_GetCode(f);
int res = super_init_without_args(f, code, &type, &obj);
Py_DECREF(code);
if (res < 0) {
return -1;
}
}
if (obj == Py_None)