6.5 Iterator Protocol

New in version 2.2.

There are only a couple of functions specifically for working with iterators.

int PyIter_Check(PyObject *o)
Return true if the object o supports the iterator protocol.

PyObject* PyIter_Next(PyObject *o)
Return value: New reference.
Return the next value from the iteration o. If the object is an iterator, this retrieves the next value from the iteration, and returns NULL with no exception set if there are no remaining items. If the object is not an iterator, TypeError is raised, or if there is an error in retrieving the item, returns NULL and passes along the exception.

To write a loop which iterates over an iterator, the C code should look something like this:

PyObject *iterator = ...;
PyObject *item;

while (item = PyIter_Next(iter)) {
    /* do something with item */
}
if (PyErr_Occurred()) {
    /* propogate error */
}
else {
    /* continue doing useful work */
}

\section{Buffer Protocol \label{abstract-buffer}}

\begin{cfuncdesc}{int}{PyObject_AsCharBuffer}{PyObject *obj,
                                              const char **buffer,
                                              int *buffer_len}
  Returns a pointer to a read-only memory location useable as character-
  based input.  The \var{obj} argument must support the single-segment
  character buffer interface.  On success, returns \code{1}, sets
  \var{buffer} to the memory location and \var{buffer_len} to the buffer
  length.  Returns \code{0} and sets a \exception{TypeError} on error.
  \versionadded{1.6}
\end{cfuncdesc}

\begin{cfuncdesc}{int}{PyObject_AsReadBuffer}{PyObject *obj,
                                              const char **buffer,
                                              int *buffer_len}
  Returns a pointer to a read-only memory location containing
  arbitrary data.  The \var{obj} argument must support the
  single-segment readable buffer interface.  On success, returns
  \code{1}, sets \var{buffer} to the memory location and \var{buffer_len}
  to the buffer length.  Returns \code{0} and sets a
  \exception{TypeError} on error.
  \versionadded{1.6}
\end{cfuncdesc}

\begin{cfuncdesc}{int}{PyObject_CheckReadBuffer}{PyObject *o}
  Returns \code{1} if \var{o} supports the single-segment readable
  buffer interface.  Otherwise returns \code{0}.
  \versionadded{2.2}
\enc{cfuncdesc}

\begin{cfuncdesc}{int}{PyObject_AsWriteBuffer}{PyObject *obj,
                                               const char **buffer,
                                               int *buffer_len}
  Returns a pointer to a writeable memory location.  The \var{obj}
  argument must support the single-segment, character buffer
  interface.  On success, returns \code{1}, sets \var{buffer} to the
  memory location and \var{buffer_len} to the buffer length.  Returns
  \code{0} and sets a \exception{TypeError} on error.
  \versionadded{1.6}
\end{cfuncdesc}
See About this document... for information on suggesting changes.