Crash using Python 2.0 Extension

Fredrik Lundh fredrik at effbot.org
Thu Jan 25 14:20:01 EST 2001


Ken Koller wrote:
> I originally wrote the routine below to return Py_None, but the
> interpretter would crash after calling the routine several times (maybe
> 100-200) in a row.

you mean like

    static PyObject * pt_pSetModule(PyObject * self, PyObject * args)
    {
        return Py_None;
    }

this doesn't work -- Python expects your function to own a
reference to the object you'll returning, and will decrement
the reference counter once it's done with the return value.
When the return value reaches zero, the None object is
removed, and anything can happen.

(in a stock interpreter, there already are 100-200 references
to None when your program starts running. sys.getrefcount(None)
will give you the exact number for your setup).

But if you look in the library sources (*always* do this when you
cannot figure out how to use the C API), you'll notice that many
functions/methods do return Py_None -- but they all do one very
important thing before doing so:

    Py_INCREF(Py_None); /* get another reference to None */
    return Py_None; /* return an owned reference */

for more info, see:
http://www.python.org/doc/current/ext/refcounts.html
(especially "ownership rules")

Cheers /F

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list