Warning about "for line in file:"

Jason Orendorff jason at jorendorff.com
Wed Feb 20 15:01:43 EST 2002


Just van Rossum wrote:
> It took me a while to understand what you meant, and the followups 
> didn't make it much clearer either... But now that I do, I'm just as 
> baffled as you are...
> 
> Here's what happens on my box:
> [...]
>
> This is highly unintuitive to me, indeed so much so that I would like to 
> call it a bug!

I agree!  This could be improved by having file.__iter__()
always return the same object.  But that doesn't solve the problem
in full.

One possibility is to change file.__iter__() to return
iter(file.readline, ''), and have users call file.xreadlines()
explicitly, and accept the semantic oddness, if they need the
extra speed.  :-\

Another possible hack would be to have xreadlines.next() call
file.seek() on the underlying file object, to make sure the two
are in sync.  That sounds like a pain to me.

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list