Skip to content

Commit 24b8bad

Browse files
authored
bpo-40703: Let PyType_FromSpec() set "type.__module__" only if it is not set yet. (GH-20273)
1 parent ec88e1b commit 24b8bad

File tree

2 files changed

+22
-15
lines changed

2 files changed

+22
-15
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
The PyType_FromSpec*() functions no longer overwrite the type's "__module__" attribute
2+
if it is set via "Py_tp_members" or "Py_tp_getset".

Objects/typeobject.c

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3067,23 +3067,28 @@ PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)
30673067
}
30683068

30693069
/* Set type.__module__ */
3070-
s = strrchr(spec->name, '.');
3071-
if (s != NULL) {
3072-
int err;
3073-
modname = PyUnicode_FromStringAndSize(
3074-
spec->name, (Py_ssize_t)(s - spec->name));
3075-
if (modname == NULL) {
3070+
if (_PyDict_GetItemIdWithError(type->tp_dict, &PyId___module__) == NULL) {
3071+
if (PyErr_Occurred()) {
30763072
goto fail;
30773073
}
3078-
err = _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname);
3079-
Py_DECREF(modname);
3080-
if (err != 0)
3081-
goto fail;
3082-
} else {
3083-
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3084-
"builtin type %.200s has no __module__ attribute",
3085-
spec->name))
3086-
goto fail;
3074+
s = strrchr(spec->name, '.');
3075+
if (s != NULL) {
3076+
int err;
3077+
modname = PyUnicode_FromStringAndSize(
3078+
spec->name, (Py_ssize_t)(s - spec->name));
3079+
if (modname == NULL) {
3080+
goto fail;
3081+
}
3082+
err = _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname);
3083+
Py_DECREF(modname);
3084+
if (err != 0)
3085+
goto fail;
3086+
} else {
3087+
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3088+
"builtin type %.200s has no __module__ attribute",
3089+
spec->name))
3090+
goto fail;
3091+
}
30873092
}
30883093

30893094
return (PyObject*)res;

0 commit comments

Comments
 (0)