PyNumber_Int screwing Object.

Tim Peters tim.one at comcast.net
Sun Oct 5 21:36:26 EDT 2003


[José Rui Faustino de Sousa]
> This code snippet is broken in the case that the argument passed is a
> complex number
>
> PyObject* tmp = Py_None;
>
> tmp=PyNumber_Int(object);
> tmp=PyObject_GetAttrString(object,"real");

That's incorrect use of the Python C API:  the return value of every call
made to a Python C API function must be checked for an error value, and if
an error value is returned the caller must either explicitly clear the
error, or return its own error value to its caller.

> it wreaks havoc on Python making it fail in weird ways.

So would dereferencing a NULL pointer <wink -- but you're coding in C here
now, not Python, and any deviation from the rules can cause anything up to
and including crashes -- C is utterly unforgiving>.

> If I insert the line between the other two
>
> if(!tmp) PyErr_Clear();
>
> things seem to work.

In that case you're doing the "must either explicitly clear the error"
choice, and it will work fine.  Note that you also need to check the result
of PyObject_GetAttrString() for an error return.

You can never skip these checks.  Even if you don't think an error "should
be" possible, an error is possible (for example, virtually any call can
return an error code due to malloc() running out of memory 10 levels deep).






More information about the Python-list mailing list