Lazy "for line in f" ?

Christoph Haas email at christoph-haas.de
Sun Jul 22 12:34:54 EDT 2007


On Sun, Jul 22, 2007 at 09:10:50AM -0700, Alexandre Ferrieux wrote:
> I'm a total newbie in Python, but did give quite a try to the
> documentation before coming here.
> Sorry if I missed the obvious.
> 
> The Tutorial says about the "for line in f" idiom that it is "space-
> efficient".
> Short of further explanation, I interpret this as "doesn't read the
> whole file before spitting out lines".

Correct. It reads one line at a time (as an "iterator") and returns it.

> In other words, I would say "lazy". Which would be a Good Thing, a
> much nicer idiom than the usual while loop calling readline()...

The space-efficiency is similar. The faux pas would rather to read the
whole file with readlines().

> But when I use it on the standard input, be it the tty or a pipe, it
> seems to wait for EOF before yielding the first line.

Standard input is a weird thing in Python. Try sending two EOFs
(Ctrl-D). There is some internal magic with two loops checking for EOF.
It's submitted as a bug report bug the developers denied a solution.
Otherwise it's fine. In a pipe you shouldn't even notice.

 Christoph




More information about the Python-list mailing list