[Python-Dev] Error checking in init<module> functions

Thomas Heller theller at python.net
Fri Apr 22 16:57:26 CEST 2005


I always wondered why there usually is very sloppy error checking in
init<module> functions.  Usually it goes like this (I removed
declarations and some other lines for clarity):

PyMODINIT_FUNC
PyInit_zlib(void)
{
    m = Py_InitModule4("zlib", zlib_methods,
		       zlib_module_documentation,
		       (PyObject*)NULL,PYTHON_API_VERSION);

    ZlibError = PyErr_NewException("zlib.error", NULL, NULL);
    if (ZlibError != NULL) {
        Py_INCREF(ZlibError);
	PyModule_AddObject(m, "error", ZlibError);
    }
    PyModule_AddIntConstant(m, "MAX_WBITS", MAX_WBITS);
    PyModule_AddIntConstant(m, "DEFLATED", DEFLATED);

    ver = PyString_FromString(ZLIB_VERSION);
    if (ver != NULL)
	PyModule_AddObject(m, "ZLIB_VERSION", ver);

    PyModule_AddStringConstant(m, "__version__", "1.0");
}

Why isn't the result checked in the PyModule_... functions?
Why is the failure of PyErr_NewException silently ignored?
The problem is that when one of these things fail (although they are
probably supposed to NOT fail) you end up with a module missing
something, without any error message.

What would be the correct thing to do - I assume something like

     if (PyModule_AddIntConstant(m, "MAX_WBITS", MAX_WBITS)) {
         PyErr_Print();
         return;
     }

Thomas



More information about the Python-Dev mailing list