blob: fb2a71cf1a825a85205c09b2d04abfc57d9b7530 [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
Raymond Hettinger632d6922015-05-11 10:22:20 -070017 This function can return a false positive in the case of old-style
18 classes because those classes always define a :c:member:`tp_iternext`
19 slot with logic that either invokes a :meth:`next` method or raises
20 a :exc:`TypeError`.
Georg Brandlf6842722008-01-19 22:08:21 +000021
Sandro Tosi98ed08f2012-01-14 16:42:02 +010022.. c:function:: PyObject* PyIter_Next(PyObject *o)
Georg Brandlf6842722008-01-19 22:08:21 +000023
Raymond Hettinger8b1701d2013-10-09 22:39:11 -070024 Return the next value from the iteration *o*. The object must be an iterator
25 (it is up to the caller to check this). If there are no remaining values,
26 returns *NULL* with no exception set. If an error occurs while retrieving
27 the item, returns *NULL* and passes along the exception.
Georg Brandlf6842722008-01-19 22:08:21 +000028
29To write a loop which iterates over an iterator, the C code should look
30something like this::
31
32 PyObject *iterator = PyObject_GetIter(obj);
33 PyObject *item;
34
35 if (iterator == NULL) {
36 /* propagate error */
37 }
38
39 while (item = PyIter_Next(iterator)) {
40 /* do something with item */
41 ...
42 /* release reference when done */
43 Py_DECREF(item);
44 }
45
46 Py_DECREF(iterator);
47
48 if (PyErr_Occurred()) {
49 /* propagate error */
50 }
51 else {
52 /* continue doing useful work */
53 }