Skip to content

bpo-40137: Optimize _PyType_GetModuleByDef() loop #25505

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 21, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 21 additions & 5 deletions Objects/typeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1987,14 +1987,20 @@ mro_invoke(PyTypeObject *type)

new_mro = PySequence_Tuple(mro_result);
Py_DECREF(mro_result);
if (new_mro == NULL)
if (new_mro == NULL) {
return NULL;
}

if (custom && mro_check(type, new_mro) < 0) {
if (PyTuple_GET_SIZE(new_mro) == 0) {
Py_DECREF(new_mro);
PyErr_Format(PyExc_TypeError, "type MRO must not be empty");
return NULL;
}

if (custom && mro_check(type, new_mro) < 0) {
Py_DECREF(new_mro);
return NULL;
}
return new_mro;
}

Expand Down Expand Up @@ -2034,8 +2040,9 @@ mro_internal(PyTypeObject *type, PyObject **p_old_mro)
new_mro = mro_invoke(type); /* might cause reentrance */
reent = (type->tp_mro != old_mro);
Py_XDECREF(old_mro);
if (new_mro == NULL)
if (new_mro == NULL) {
return -1;
}

if (reent) {
Py_DECREF(new_mro);
Expand Down Expand Up @@ -3590,9 +3597,17 @@ PyObject *
_PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)
{
assert(PyType_Check(type));

PyObject *mro = type->tp_mro;
// The type must be ready
assert(mro != NULL);
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(mro); i++) {
assert(PyTuple_Check(mro));
// mro_invoke() ensures that the type MRO cannot be empty, so we don't have
// to check i < PyTuple_GET_SIZE(mro) at the first loop iteration.
assert(PyTuple_GET_SIZE(mro) >= 1);

Py_ssize_t i = 0;
do {
PyObject *super = PyTuple_GET_ITEM(mro, i);
// _PyType_GetModuleByDef() must only be called on a heap type created
// by PyType_FromModuleAndSpec() or on its subclasses.
Expand All @@ -3605,7 +3620,8 @@ _PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)
if (module && PyModule_GetDef(module) == def) {
return module;
}
}
i++;
} while (i < PyTuple_GET_SIZE(mro));

PyErr_Format(
PyExc_TypeError,
Expand Down