Debian Codegraph @

Doc/c-api/iter.rst

raw
1 .. highlight:: c
2
3 .. _iterator:
4
5 Iterator Protocol
6 =================
7
8 There are two functions specifically for working with iterators.
9
10 .. c:function:: int PyIter_Check(PyObject *o)
11
12 Return non-zero if the object *o* can be safely passed to
13 :c:func:`PyIter_Next`, and ``0`` otherwise. This function always succeeds.
14
15 .. c:function:: int PyAIter_Check(PyObject *o)
16
17 Return non-zero if the object *o* provides the :class:`AsyncIterator`
18 protocol, and ``0`` otherwise. This function always succeeds.
19
20 .. versionadded:: 3.10
21
22 .. c:function:: PyObject* PyIter_Next(PyObject *o)
23
24 Return the next value from the iterator *o*. The object must be an iterator
25 according to :c:func:`PyIter_Check` (it is up to the caller to check this).
26 If there are no remaining values, returns ``NULL`` with no exception set.
27 If an error occurs while retrieving the item, returns ``NULL`` and passes
28 along the exception.
29
30 To write a loop which iterates over an iterator, the C code should look
31 something like this::
32
33 PyObject *iterator = PyObject_GetIter(obj);
34 PyObject *item;
35
36 if (iterator == NULL) {
37 /* propagate error */
38 }
39
40 while ((item = PyIter_Next(iterator))) {
41 /* do something with item */
42 ...
43 /* release reference when done */
44 Py_DECREF(item);
45 }
46
47 Py_DECREF(iterator);
48
49 if (PyErr_Occurred()) {
50 /* propagate error */
51 }
52 else {
53 /* continue doing useful work */
54 }
55
56
57 .. c:type:: PySendResult
58
59 The enum value used to represent different results of :c:func:`PyIter_Send`.
60
61 .. versionadded:: 3.10
62
63
64 .. c:function:: PySendResult PyIter_Send(PyObject *iter, PyObject *arg, PyObject **presult)
65
66 Sends the *arg* value into the iterator *iter*. Returns:
67
68 - ``PYGEN_RETURN`` if iterator returns. Return value is returned via *presult*.
69 - ``PYGEN_NEXT`` if iterator yields. Yielded value is returned via *presult*.
70 - ``PYGEN_ERROR`` if iterator has raised and exception. *presult* is set to ``NULL``.
71
72 .. versionadded:: 3.10