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