Georg Brandl | 54a3faa | 2008-01-20 09:30:57 +0000 | [diff] [blame] | 1 | .. highlightlang:: c |
| 2 | |
| 3 | .. _iterator: |
| 4 | |
| 5 | Iterator Protocol |
| 6 | ================= |
| 7 | |
Raymond Hettinger | 8ee7708 | 2013-10-09 22:42:46 -0700 | [diff] [blame^] | 8 | There are two functions specifically for working with iterators. |
Georg Brandl | 54a3faa | 2008-01-20 09:30:57 +0000 | [diff] [blame] | 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 | |
Raymond Hettinger | 8ee7708 | 2013-10-09 22:42:46 -0700 | [diff] [blame^] | 17 | Return the next value from the iteration *o*. The object must be an iterator |
| 18 | (it is up to the caller to check this). If there are no remaining values, |
| 19 | returns *NULL* with no exception set. If an error occurs while retrieving |
| 20 | the item, returns *NULL* and passes along the exception. |
Georg Brandl | 54a3faa | 2008-01-20 09:30:57 +0000 | [diff] [blame] | 21 | |
| 22 | To write a loop which iterates over an iterator, the C code should look |
| 23 | something like this:: |
| 24 | |
| 25 | PyObject *iterator = PyObject_GetIter(obj); |
| 26 | PyObject *item; |
| 27 | |
| 28 | if (iterator == NULL) { |
| 29 | /* propagate error */ |
| 30 | } |
| 31 | |
| 32 | while (item = PyIter_Next(iterator)) { |
| 33 | /* do something with item */ |
| 34 | ... |
| 35 | /* release reference when done */ |
| 36 | Py_DECREF(item); |
| 37 | } |
| 38 | |
| 39 | Py_DECREF(iterator); |
| 40 | |
| 41 | if (PyErr_Occurred()) { |
| 42 | /* propagate error */ |
| 43 | } |
| 44 | else { |
| 45 | /* continue doing useful work */ |
| 46 | } |