symbian-qemu-0.9.1-12/python-2.6.1/Doc/c-api/iter.rst
changeset 1 2fb8b9db1c86
equal deleted inserted replaced
0:ffa851df0825 1:2fb8b9db1c86
       
     1 .. highlightlang:: c
       
     2 
       
     3 .. _iterator:
       
     4 
       
     5 Iterator Protocol
       
     6 =================
       
     7 
       
     8 .. versionadded:: 2.2
       
     9 
       
    10 There are only a couple of functions specifically for working with iterators.
       
    11 
       
    12 
       
    13 .. cfunction:: int PyIter_Check(PyObject *o)
       
    14 
       
    15    Return true if the object *o* supports the iterator protocol.
       
    16 
       
    17 
       
    18 .. cfunction:: PyObject* PyIter_Next(PyObject *o)
       
    19 
       
    20    Return the next value from the iteration *o*.  If the object is an iterator,
       
    21    this retrieves the next value from the iteration, and returns *NULL* with no
       
    22    exception set if there are no remaining items.  If the object is not an
       
    23    iterator, :exc:`TypeError` is raised, or if there is an error in retrieving the
       
    24    item, returns *NULL* and passes along the exception.
       
    25 
       
    26 To write a loop which iterates over an iterator, the C code should look
       
    27 something like this::
       
    28 
       
    29    PyObject *iterator = PyObject_GetIter(obj);
       
    30    PyObject *item;
       
    31 
       
    32    if (iterator == NULL) {
       
    33        /* propagate error */
       
    34    }
       
    35 
       
    36    while (item = PyIter_Next(iterator)) {
       
    37        /* do something with item */
       
    38        ...
       
    39        /* release reference when done */
       
    40        Py_DECREF(item);
       
    41    }
       
    42 
       
    43    Py_DECREF(iterator);
       
    44 
       
    45    if (PyErr_Occurred()) {
       
    46        /* propagate error */
       
    47    }
       
    48    else {
       
    49        /* continue doing useful work */
       
    50    }