Skip to content
Merged
Show file tree
Hide file tree
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
16 changes: 16 additions & 0 deletions Lib/test/test_capi/test_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,22 @@ class Z(C1, A2): pass
_testcapi.pytype_getbasebytoken(
'not a type', id(self), True, False)

def test_get_module_by_def(self):
heaptype = _testcapi.create_type_with_token('_testcapi.H', 0)
mod = _testcapi.pytype_getmodulebydef(heaptype)
self.assertIs(mod, _testcapi)

class H1(heaptype): pass
mod = _testcapi.pytype_getmodulebydef(H1)
self.assertIs(mod, _testcapi)

with self.assertRaises(TypeError):
_testcapi.pytype_getmodulebydef(int)

class H2(int): pass
with self.assertRaises(TypeError):
_testcapi.pytype_getmodulebydef(H2)

def test_freeze(self):
# test PyType_Freeze()
type_freeze = _testcapi.type_freeze
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix regression where :c:func:`PyType_GetModuleByDef` returns NULL without
setting :exc:`TypeError` when a static type is passed.
8 changes: 8 additions & 0 deletions Modules/_testcapi/heaptype.c
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,13 @@ pytype_getbasebytoken(PyObject *self, PyObject *args)
return NULL;
}

static PyObject *
pytype_getmodulebydef(PyObject *self, PyObject *type)
{
PyObject *mod = PyType_GetModuleByDef((PyTypeObject *)type, _testcapimodule);
return Py_XNewRef(mod);
}


static PyMethodDef TestMethods[] = {
{"pytype_fromspec_meta", pytype_fromspec_meta, METH_O},
Expand All @@ -538,6 +545,7 @@ static PyMethodDef TestMethods[] = {
{"create_type_with_token", create_type_with_token, METH_VARARGS},
{"get_tp_token", get_tp_token, METH_O},
{"pytype_getbasebytoken", pytype_getbasebytoken, METH_VARARGS},
{"pytype_getmodulebydef", pytype_getmodulebydef, METH_O},
{NULL},
};

Expand Down
16 changes: 9 additions & 7 deletions Objects/typeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -5399,7 +5399,7 @@ PyType_GetModuleByDef(PyTypeObject *type, PyModuleDef *def)
if (!_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE)) {
// type_ready_mro() ensures that no heap type is
// contained in a static type MRO.
return NULL;
goto error;
}
else {
PyHeapTypeObject *ht = (PyHeapTypeObject*)type;
Expand Down Expand Up @@ -5439,13 +5439,15 @@ PyType_GetModuleByDef(PyTypeObject *type, PyModuleDef *def)
}
END_TYPE_LOCK();

if (res == NULL) {
PyErr_Format(
PyExc_TypeError,
"PyType_GetModuleByDef: No superclass of '%s' has the given module",
type->tp_name);
if (res != NULL) {
return res;
}
return res;
error:
PyErr_Format(
PyExc_TypeError,
"PyType_GetModuleByDef: No superclass of '%s' has the given module",
type->tp_name);
return NULL;
}


Expand Down
Loading