blob: 88ac0c1b2ffc8ba93703359e767f2f865d362091 [file] [log] [blame]
Georg Brandlf6842722008-01-19 22:08:21 +00001.. highlightlang:: c
2
3.. _iterator:
4
5Iterator Protocol
6=================
7
8.. versionadded:: 2.2
9
10There are only a couple of functions specifically for working with iterators.
11
12
Sandro Tosi98ed08f2012-01-14 16:42:02 +010013.. c:function:: int PyIter_Check(PyObject *o)
Georg Brandlf6842722008-01-19 22:08:21 +000014
15 Return true if the object *o* supports the iterator protocol.
16
17
Sandro Tosi98ed08f2012-01-14 16:42:02 +010018.. c:function:: PyObject* PyIter_Next(PyObject *o)
Georg Brandlf6842722008-01-19 22:08:21 +000019
20 Return the next value from the iteration *o*. If the object is an iterator,
21 this retrieves the next value from the iteration, and returns *NULL* with no
22 exception set if there are no remaining items. If the object is not an
23 iterator, :exc:`TypeError` is raised, or if there is an error in retrieving the
24 item, returns *NULL* and passes along the exception.
25
26To write a loop which iterates over an iterator, the C code should look
27something like this::
28
29 PyObject *iterator = PyObject_GetIter(obj);
30 PyObject *item;
31
32 if (iterator == NULL) {
33 /* propagate error */
34 }
35
36 while (item = PyIter_Next(iterator)) {
37 /* do something with item */
38 ...
39 /* release reference when done */
40 Py_DECREF(item);
41 }
42
43 Py_DECREF(iterator);
44
45 if (PyErr_Occurred()) {
46 /* propagate error */
47 }
48 else {
49 /* continue doing useful work */
50 }