Georg Brandl | f684272 | 2008-01-19 22:08:21 +0000 | [diff] [blame] | 1 | .. highlightlang:: c |
| 2 | |
| 3 | .. _iterator: |
| 4 | |
| 5 | Iterator Protocol |
| 6 | ================= |
| 7 | |
| 8 | .. versionadded:: 2.2 |
| 9 | |
Raymond Hettinger | 8b1701d | 2013-10-09 22:39:11 -0700 | [diff] [blame] | 10 | There are two functions specifically for working with iterators. |
Georg Brandl | f684272 | 2008-01-19 22:08:21 +0000 | [diff] [blame] | 11 | |
| 12 | |
Sandro Tosi | 98ed08f | 2012-01-14 16:42:02 +0100 | [diff] [blame] | 13 | .. c:function:: int PyIter_Check(PyObject *o) |
Georg Brandl | f684272 | 2008-01-19 22:08:21 +0000 | [diff] [blame] | 14 | |
| 15 | Return true if the object *o* supports the iterator protocol. |
| 16 | |
| 17 | |
Sandro Tosi | 98ed08f | 2012-01-14 16:42:02 +0100 | [diff] [blame] | 18 | .. c:function:: PyObject* PyIter_Next(PyObject *o) |
Georg Brandl | f684272 | 2008-01-19 22:08:21 +0000 | [diff] [blame] | 19 | |
Raymond Hettinger | 8b1701d | 2013-10-09 22:39:11 -0700 | [diff] [blame] | 20 | 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 Brandl | f684272 | 2008-01-19 22:08:21 +0000 | [diff] [blame] | 24 | |
| 25 | To write a loop which iterates over an iterator, the C code should look |
| 26 | something 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 | } |