File iteration in 2.2

Clarence Gardner clarence at netlojix.com
Wed Aug 28 18:12:15 CEST 2002


In article <3D6C4FFA.98ED35F9 at alcyone.com>,
	Erik Max Francis <max at alcyone.com> writes:
> 
> This seems to confuse a fair number of people; file iterators are really
> intended work like the F.xreadlines() method, which is an optimized form
> of F.readlines() method to read in chunks at a time (as you've
> discovered).
> 
> I think the answer you'd get is that the .readlines/.xreadlines are
> really intended when you want to iterate over the _entire_ file no
> matter what.  .readlines reads _all_ the lines in at once, not giving

Your argument rests on the assertion "file iterators are really
intended work like the F.xreadlines() method". Is this true? I
would hope not. xreadlines was a hack, intended to provide some
kind of iteration over a file before there was an iteration protocol.
That to me does not imply that, upon implementing the iteration
protocol, a file iterator should behave like xreadlines.

It is possible to break out of a loop over other kinds of iterators,
and then continue them:
    >>> d = {1:1, 2:2, 3:3}
    >>> i = d.__iter__()
    >>> for key in i:
    ...     print key
    ...     break
    ...
    1
    >>> i.next()
    2
    >>> i.next()
    3
    >>> i.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration

Why should a file iterator be different?

(As an aside, when doing that example, I was amazed to see that the
built-in list type does not provide an iterator...)


-- 
Clarence Gardner
Software Engineer
NetLojix Communications
cgardner at netlojix.com



More information about the Python-list mailing list