[Python-ideas] "While" suggestion

Bill Janssen janssen at parc.com
Thu Jul 3 18:57:03 CEST 2008


> while True:
>     data = my_file.read(1024)
>     if not data: break
>     do_something(data)
> 
> which seems perfectly acceptable and in keeping with TOOWTDI by
> minimizing the number of loop constructs in the language.
> It obviously avoids the distasteful duplication of "data = my_file.read(1024)".

You're right, it's the way it has to be done, but I personally find it
awful code.  "while True" is a do-forever, so that's what you read
first, but that's not really what we want to write.  Then we read, OK,
but then we break out of the forever loop, then we don't, and do
something with the data we read.  It's a mess.

What I'd like to be able to write is something like this:

     while my_file.has_more_data():
	 do_something_with_data(my_file.read(1024))

For instance:

     for line in open(filename):
         do_something_with_data(line)

Which, in its non-line form, is pretty much what Josiah suggested.

+1 for adding "blocked_reader" as a static method on the "file" class,
or perhaps one of the IOStream ABC classes.

Bill



More information about the Python-ideas mailing list