Iterators

Duncan Booth duncan.booth at invalid.invalid
Fri Oct 16 14:22:21 CEST 2009


Chris Rebert <clp2 at rebertia.com> wrote:

> Essentially, file iterators are dumb and don't keep track of where in
> the file the next line starts, instead relying on their associated
> file object to keep track of the current position in the file; the
> iterator's state is little more than a reference to its associated
> file object. When asked for the "next" line, a file iterator just
> reads forward to the next newline from the file object's current
> position, changing the current position as tracked by the file object
> as a side-effect. Thus, using multiple iterators to the same file
> object can have the results you're seeing when these side-effects
> interact.

Nothing 'dumb' or 'smart' about it: it is simply that a file object is 
already an iterator. Trying to create an iterator from an existing iterator 
in Python never duplicates the iterator.

>>> f = open('somefile')
>>> iter(f) is f
True


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list