Skip to content

Commit 40b33c6

Browse files
committed
Removed fatal errors from Py_Initmodule4() (and thus from
Py_Initmodule(), which is a macro wrapper around it). The return value is now a NULL pointer if the initialization failed. This may make old modules fail with a SEGFAULT, since they don't expect this kind of failure. That's OK, since (a) it "never" happens, and (b) they would fail with a fatal error otherwise, anyway. Tons of extension modules should now check the return value of Py_Initmodule*() -- that's on my TODO list.
1 parent aee094c commit 40b33c6

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

Python/modsupport.c

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,17 @@ typedef extended va_double;
3939
typedef double va_double;
4040
#endif
4141

42-
/* initmodule4() parameters:
42+
/* Py_InitModule4() parameters:
4343
- name is the module name
4444
- methods is the list of top-level functions
4545
- doc is the documentation string
4646
- passthrough is passed as self to functions defined in the module
4747
- api_version is the value of PYTHON_API_VERSION at the time the
4848
module was compiled
49+
50+
Return value is a borrowed reference to the module object; or NULL
51+
if an error occurred (in Python 1.4 and before, errors were fatal).
52+
Errors may still leak memory.
4953
*/
5054

5155
static char api_version_warning[] =
@@ -65,25 +69,21 @@ Py_InitModule4(name, methods, doc, passthrough, module_api_version)
6569
if (module_api_version != PYTHON_API_VERSION)
6670
fprintf(stderr, api_version_warning,
6771
name, PYTHON_API_VERSION, name, module_api_version);
68-
if ((m = PyImport_AddModule(name)) == NULL) {
69-
fprintf(stderr, "initializing module: %s\n", name);
70-
Py_FatalError("can't create a module");
71-
}
72+
if ((m = PyImport_AddModule(name)) == NULL)
73+
return NULL;
7274
d = PyModule_GetDict(m);
7375
for (ml = methods; ml->ml_name != NULL; ml++) {
7476
v = PyCFunction_New(ml, passthrough);
75-
if (v == NULL ||
76-
PyDict_SetItemString(d, ml->ml_name, v) != 0)
77-
{
78-
fprintf(stderr, "initializing module: %s\n", name);
79-
Py_FatalError("can't initialize module");
80-
}
77+
if (v == NULL)
78+
return NULL;
79+
if (PyDict_SetItemString(d, ml->ml_name, v) != 0)
80+
return NULL;
8181
Py_DECREF(v);
8282
}
8383
if (doc != NULL) {
8484
v = PyString_FromString(doc);
8585
if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0)
86-
Py_FatalError("can't add doc string");
86+
return NULL;
8787
Py_DECREF(v);
8888
}
8989
return m;

0 commit comments

Comments
 (0)