← 返回首页
PEP 234 – Iterators | peps.python.org Following system colour scheme Selected dark colour scheme Selected light colour scheme

Python Enhancement Proposals

Toggle light / dark / auto colour theme PEP 234 – Iterators

PEP 234 – Iterators

Author: Ka-Ping Yee <ping at zesty.ca>, Guido van Rossum <guido at python.org> Status: Final Type: Standards Track Created: 30-Jan-2001 Python-Version: 2.1 Post-History: 30-Apr-2001 Table of Contents

Abstract

This document proposes an iteration interface that objects can provide to control the behaviour of for loops. Looping is customized by providing a method that produces an iterator object. The iterator provides a get next value operation that produces the next item in the sequence each time it is called, raising an exception when no more items are available.

In addition, specific iterators over the keys of a dictionary and over the lines of a file are proposed, and a proposal is made to allow spelling dict.has_key(key) as key in dict.

Note: this is an almost complete rewrite of this PEP by the second author, describing the actual implementation checked into the trunk of the Python 2.2 CVS tree. It is still open for discussion. Some of the more esoteric proposals in the original version of this PEP have been withdrawn for now; these may be the subject of a separate PEP in the future.

C API Specification

A new exception is defined, StopIteration, which can be used to signal the end of an iteration.

A new slot named tp_iter for requesting an iterator is added to the type object structure. This should be a function of one PyObject * argument returning a PyObject *, or NULL. To use this slot, a new C API function PyObject_GetIter() is added, with the same signature as the tp_iter slot function.

Another new slot, named tp_iternext, is added to the type structure, for obtaining the next value in the iteration. To use this slot, a new C API function PyIter_Next() is added. The signature for both the slot and the API function is as follows, although the NULL return conditions differ: the argument is a PyObject * and so is the return value. When the return value is non-NULL, it is the next value in the iteration. When it is NULL, then for the tp_iternext slot there are three possibilities:

The higher-level PyIter_Next() function clears the StopIteration exception (or derived exception) when it occurs, so its NULL return conditions are simpler:

Iterators implemented in C should not implement a next() method with similar semantics as the tp_iternext slot! When the type’s dictionary is initialized (by PyType_Ready()), the presence of a tp_iternext slot causes a method next() wrapping that slot to be added to the type’s tp_dict. (Exception: if the type doesn’t use PyObject_GenericGetAttr() to access instance attributes, the next() method in the type’s tp_dict may not be seen.) (Due to a misunderstanding in the original text of this PEP, in Python 2.2, all iterator types implemented a next() method that was overridden by the wrapper; this has been fixed in Python 2.3.)

To ensure binary backwards compatibility, a new flag Py_TPFLAGS_HAVE_ITER is added to the set of flags in the tp_flags field, and to the default flags macro. This flag must be tested before accessing the tp_iter or tp_iternext slots. The macro PyIter_Check() tests whether an object has the appropriate flag set and has a non-NULL tp_iternext slot. There is no such macro for the tp_iter slot (since the only place where this slot is referenced should be PyObject_GetIter(), and this can check for the Py_TPFLAGS_HAVE_ITER flag directly).

(Note: the tp_iter slot can be present on any object; the tp_iternext slot should only be present on objects that act as iterators.)

For backwards compatibility, the PyObject_GetIter() function implements fallback semantics when its argument is a sequence that does not implement a tp_iter function: a lightweight sequence iterator object is constructed in that case which iterates over the items of the sequence in the natural order.

The Python bytecode generated for for loops is changed to use new opcodes, GET_ITER and FOR_ITER, that use the iterator protocol rather than the sequence protocol to get the next value for the loop variable. This makes it possible to use a for loop to loop over non-sequence objects that support the tp_iter slot. Other places where the interpreter loops over the values of a sequence should also be changed to use iterators.

Iterators ought to implement the tp_iter slot as returning a reference to themselves; this is needed to make it possible to use an iterator (as opposed to a sequence) in a for loop.

Iterator implementations (in C or in Python) should guarantee that once the iterator has signalled its exhaustion, subsequent calls to tp_iternext or to the next() method will continue to do so. It is not specified whether an iterator should enter the exhausted state when an exception (other than StopIteration) is raised. Note that Python cannot guarantee that user-defined or 3rd party iterators implement this requirement correctly.

Python API Specification

The StopIteration exception is made visible as one of the standard exceptions. It is derived from Exception.

A new built-in function is defined, iter(), which can be called in two ways:

Iterator objects returned by either form of iter() have a next() method. This method either returns the next value in the iteration, or raises StopIteration (or a derived exception class) to signal the end of the iteration. Any other exception should be considered to signify an error and should be propagated normally, not taken to mean the end of the iteration.

Classes can define how they are iterated over by defining an __iter__() method; this should take no additional arguments and return a valid iterator object. A class that wants to be an iterator should implement two methods: a next() method that behaves as described above, and an __iter__() method that returns self.

The two methods correspond to two distinct protocols:

  1. An object can be iterated over with for if it implements __iter__() or __getitem__().
  2. An object can function as an iterator if it implements next().

Container-like objects usually support protocol 1. Iterators are currently required to support both protocols. The semantics of iteration come only from protocol 2; protocol 1 is present to make iterators behave like sequences; in particular so that code receiving an iterator can use a for-loop over the iterator.

Dictionary Iterators

Other mappings, if they support iterators at all, should also iterate over the keys. However, this should not be taken as an absolute rule; specific applications may have different requirements.

File Iterators

The following proposal is useful because it provides us with a good answer to the complaint that the common idiom to iterate over the lines of a file is ugly and slow.

This also shows that some iterators are destructive: they consume all the values and a second iterator cannot easily be created that iterates independently over the same values. You could open the file for a second time, or seek() to the beginning, but these solutions don’t work for all file types, e.g. they don’t work when the open file object really represents a pipe or a stream socket.

Because the file iterator uses an internal buffer, mixing this with other file operations (e.g. file.readline()) doesn’t work right. Also, the following code:

for line in file: if line == "\n": break for line in file: print line,

doesn’t work as you might expect, because the iterator created by the second for-loop doesn’t take the buffer read-ahead by the first for-loop into account. A correct way to write this is:

it = iter(file) for line in it: if line == "\n": break for line in it: print line,

(The rationale for these restrictions are that for line in file ought to become the recommended, standard way to iterate over the lines of a file, and this should be as fast as can be. The iterator version is considerable faster than calling readline(), due to the internal buffer in the iterator.)

Rationale

If all the parts of the proposal are included, this addresses many concerns in a consistent and flexible fashion. Among its chief virtues are the following four – no, five – no, six – points:

  1. It provides an extensible iterator interface.
  2. It allows performance enhancements to list iteration.
  3. It allows big performance enhancements to dictionary iteration.
  4. It allows one to provide an interface for just iteration without pretending to provide random access to elements.
  5. It is backward-compatible with all existing user-defined classes and extension objects that emulate sequences and mappings, even mappings that only implement a subset of {__getitem__, keys, values, items}.
  6. It makes code iterating over non-sequence collections more concise and readable.

Resolved Issues

The following topics have been decided by consensus or BDFL pronouncement.

Mailing Lists

The iterator protocol has been discussed extensively in a mailing list on SourceForge:

http://lists.sourceforge.net/lists/listinfo/python-iterators

Initially, some of the discussion was carried out at Yahoo; archives are still accessible:

http://groups.yahoo.com/group/python-iter

Copyright

This document is in the public domain.

Contents


Page Source (GitHub)

Source: https://github.com/python/peps/blob/main/peps/pep-0234.rst

Last modified: 2025-02-01 08:55:40 UTC