迭代器協(xié)議?
迭代器有兩個函數(shù)。
-
int PyIter_Check(PyObject *o)?
- Part of the Stable ABI since version 3.8.
Return non-zero if the object o can be safely passed to
PyIter_Next(), and0otherwise. This function always succeeds.
-
int PyAIter_Check(PyObject *o)?
- Part of the Stable ABI since version 3.10.
Return non-zero if the object o provides the
AsyncIteratorprotocol, and0otherwise. This function always succeeds.3.10 新版功能.
-
PyObject *PyIter_Next(PyObject *o)?
- Return value: New reference. Part of the Stable ABI.
Return the next value from the iterator o. The object must be an iterator according to
PyIter_Check()(it is up to the caller to check this). If there are no remaining values, returnsNULLwith no exception set. If an error occurs while retrieving the item, returnsNULLand passes along the exception.
要為迭代器編寫一個一個循環(huán),C代碼應(yīng)該看起來像這樣
PyObject *iterator = PyObject_GetIter(obj);
PyObject *item;
if (iterator == NULL) {
/* propagate error */
}
while ((item = PyIter_Next(iterator))) {
/* do something with item */
...
/* release reference when done */
Py_DECREF(item);
}
Py_DECREF(iterator);
if (PyErr_Occurred()) {
/* propagate error */
}
else {
/* continue doing useful work */
}
-
type PySendResult?
用于代表
PyIter_Send()的不同結(jié)果的枚舉值。3.10 新版功能.
-
PySendResult PyIter_Send(PyObject *iter, PyObject *arg, PyObject **presult)?
- Part of the Stable ABI since version 3.10.
將 arg 值發(fā)送到迭代器 iter。 返回:
PYGEN_RETURN,如果迭代器返回的話。 返回值會通過 presult 來返回。PYGEN_NEXT,如果迭代器生成值的話。 生成的值會通過 presult 來返回。PYGEN_ERROR,如果迭代器引發(fā)異常的話。 presult 會被設(shè)為NULL。
3.10 新版功能.