blob: 8d1567c7b34a99ed1663dae277c8060667928e8c [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
Raymond Hettinger8b1701d2013-10-09 22:39:11 -070010There are two functions specifically for working with iterators.
Georg Brandlf6842722008-01-19 22:08:21 +000011
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
Raymond Hettinger8b1701d2013-10-09 22:39:11 -070020 Return the next value from the iteration *o*. The object must be an iterator
21 (it is up to the caller to check this). If there are no remaining values,
22 returns *NULL* with no exception set. If an error occurs while retrieving
23 the item, returns *NULL* and passes along the exception.
Georg Brandlf6842722008-01-19 22:08:21 +000024
25To write a loop which iterates over an iterator, the C code should look
26something like this::
27
28 PyObject *iterator = PyObject_GetIter(obj);
29 PyObject *item;
30
31 if (iterator == NULL) {
32 /* propagate error */
33 }
34
35 while (item = PyIter_Next(iterator)) {
36 /* do something with item */
37 ...
38 /* release reference when done */
39 Py_DECREF(item);
40 }
41
42 Py_DECREF(iterator);
43
44 if (PyErr_Occurred()) {
45 /* propagate error */
46 }
47 else {
48 /* continue doing useful work */
49 }