Skip to content

Commit 9419158

Browse files
bpo-40703: Let PyType_FromSpec() set "type.__module__" only if it is not set yet. (GH-20273) (GH-20782)
(cherry picked from commit 24b8bad)
1 parent 3b97d1b commit 9419158

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
@@ -3061,23 +3061,28 @@ PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)
30613061
}
30623062

30633063
/* Set type.__module__ */
3064-
s = strrchr(spec->name, '.');
3065-
if (s != NULL) {
3066-
int err;
3067-
modname = PyUnicode_FromStringAndSize(
3068-
spec->name, (Py_ssize_t)(s - spec->name));
3069-
if (modname == NULL) {
3064+
if (_PyDict_GetItemIdWithError(type->tp_dict, &PyId___module__) == NULL) {
3065+
if (PyErr_Occurred()) {
30703066
goto fail;
30713067
}
3072-
err = _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname);
3073-
Py_DECREF(modname);
3074-
if (err != 0)
3075-
goto fail;
3076-
} else {
3077-
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3078-
"builtin type %.200s has no __module__ attribute",
3079-
spec->name))
3080-
goto fail;
3068+
s = strrchr(spec->name, '.');
3069+
if (s != NULL) {
3070+
int err;
3071+
modname = PyUnicode_FromStringAndSize(
3072+
spec->name, (Py_ssize_t)(s - spec->name));
3073+
if (modname == NULL) {
3074+
goto fail;
3075+
}
3076+
err = _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname);
3077+
Py_DECREF(modname);
3078+
if (err != 0)
3079+
goto fail;
3080+
} else {
3081+
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
3082+
"builtin type %.200s has no __module__ attribute",
3083+
spec->name))
3084+
goto fail;
3085+
}
30813086
}
30823087

30833088
return (PyObject*)res;

0 commit comments

Comments
 (0)