[Python-Dev] refcounting vs PyModule_AddObject

Michael Hudson mwh at python.net
Wed Jun 15 14:35:35 CEST 2005


I've just fixed a bug where Py_INCREF wasn't called when it should
have been before a call to PyModule_AddObject (rev. 2.62 of
Modules/threadmodule.c).

So I went looking for other instances of the same problem.  I didn't
find any (though I don't understand how _csv.c gets away with line
1579), but what I *did* find were absolutely masses of what seemed
like unnecessary increfs.  Consider this code from _hotshot.c:

        Py_INCREF(&LogReaderType);
        PyModule_AddObject(module, "LogReaderType",
                           (PyObject *)&LogReaderType);
        Py_INCREF(&ProfilerType);
        PyModule_AddObject(module, "ProfilerType",
                           (PyObject *)&ProfilerType);

        if (ProfilerError == NULL)
            ProfilerError = PyErr_NewException("hotshot.ProfilerError",
                                               NULL, NULL);
        if (ProfilerError != NULL) {
            Py_INCREF(ProfilerError);
            PyModule_AddObject(module, "ProfilerError", ProfilerError);
        }

The first two calls are fine; it was an incref like this that was
missing in threadmodule.c.  The second seems like a reference "leak":
PyErr_NewException returns a new reference, then the
Py_INCREF/PyModule_AddObject pair is refcount neutral, so control
falls off the end of the function owning a reference to ProfilerError.

I think the Py_INCREF should just be removed, but I'm wondering if I'm
missing something...

Cheers,
mwh

-- 
  MacOSX: Sort of like a pedigree persian cat. Very sleek, very
  sexy, but a little too prone to going cross-eyed, biting you on
  your thumb and then throwing up on your trousers.
                           -- Jim's pedigree of operating systems, asr


More information about the Python-Dev mailing list