Note for exceptions in Python C API

Julien ÉLIE julien at trigofacile.com
Sat Jun 21 21:33:14 UTC 2008


Hi,

Trying to debug Python scripts, I noticed a few things.  I had to read
the Python C API in order to understand what was going on at several
places.  I think it is worthwhile to put a note here.

Especially regarding exceptions.
Functions like this one:

    PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name)
        Return value: New reference.
        Retrieve an attribute named attr_name from object o.
        Returns the attribute value on success, or NULL on failure.
        This is the equivalent of the Python expression "o.attr_name".

raise an exception in failure, even though they return NULL.  And as
exceptions accumulate from caller to caller and so on, it generates
weird issues with Python scripts.  Hard to debug afterwards!

In nnrpd/python.c:

    *methptr = PyObject_GetAttrString(PYAuthObject, (char *) methname);

can return NULL.  And even though the C code afterwards handles it,
it is not OK for Python, which has raised an exception!

It should be rewritten this way:

    if (PyObject_HasAttrString(PYAuthObject, (char *) methname) == 1) {
        *methptr = PyObject_GetAttrString(PYAuthObject, (char *) methname);
    } else {
        *methptr = NULL;
    }

It is the Python way to do that.


I will fix /some/ of these occurrences in STABLE and CURRENT.
(Because stuff like PyBuffer_FromMemory(Client.host, strlen(Client.host)),
even though Client.host is /normally/ OK, should also be taken into
consideration...  I think we can assume it is OK without verifying
it really exists...)

-- 
Julien ÉLIE

« -- Poussez pas derrière !
  -- Pas si vite devant ! » (Astérix)



More information about the inn-workers mailing list