我正在将一个C函数作为Python的扩展实现。在
我希望自行处理错误。因此,我尝试使用
我认为这可能是由于
为什么
abstract.h
中,我找到以下内容:/* ==== Iterators ================================================ */
/* Takes an object and returns an iterator for it.
This is typically a new iterator but if the argument is an iterator, this
returns itself. */
PyAPI_FUNC(PyObject *) PyObject_GetIter(PyObject *);
/* Returns 1 if the object 'obj' provides iterator protocols, and 0 otherwise.
This function always succeeds. */
PyAPI_FUNC(int) PyIter_Check(PyObject *);
当我尝试在明显不可迭代的对象(如数字)上使用PyObject_GetIter
获取迭代器时,会出现错误SystemError: <built-in function xxx> returned a result with an error set
。
static PyObject *my_method(PyObject *self, PyObject *args)
{
PyObject *obj;
PyArg_ParseTuple(args, "O", &obj)
// printf("\ncheck %d",PyIter_Check(obj)); // always 0
PyObject *iter = PyObject_GetIter(obj); // throws error
return PyLong_FromLong(0);
}
我希望自行处理错误。因此,我尝试使用
PyIter_Check
函数来测试对象是否具有迭代器。然而,无论我提供哪些对象,包括可迭代的对象,该函数都会返回0。我认为这可能是由于
PyAPI_FUNC()
宏引起的,但我在pyport.h
中找到了它,并且似乎只添加了__declspec
。为什么
PyIter_Check
函数对所有对象都返回零呢?
Py_DECREF
之外,通常您只需要这样说:PyObject *const x=Py_Foo(…); if(!x) return 0;
。 - Davis Herring