Loop-and-a-half (Re: Curious assignment behaviour)
Huaiyu Zhu
huaiyu at gauss.almadan.ibm.com
Fri Oct 12 15:56:47 EDT 2001
On Thu, 11 Oct 2001 23:33:20 +0200, Alex Martelli <aleax at aleax.it> wrote:
[...]
>
>for line in file.xreadlines():
> if line == 'end': break
> etcetc(line)
[...]
>
>while data.set(file.readline()) != 'end':
> process(data.get())
>
Alex, what's your opinion comparing these to the following?
while line = file.xreadlines(); line != 'end':
etcetc(line)
I'm pushing for this because it is not just syntactic suguar. It gives
semantic advantage as well. For example,
while x = next(); not x.is_end:
y = process(x)
if y.is_what_we_are_looking_for(): break
else:
raise "not found"
It is not equivalent to this naive version:
while 1:
x = next()
if x.is_end: break
y = process(x)
if y.is_what_we_are_looking_for(): break
else:
raise "not found"
That's because there are two breaks that have different semantical meanings.
The fully equivalent version in today's syntax has to use one extra variable
(assuming the variable _flag is not used for other purpose):
_flag = 0
while 1:
x = next()
if x.is_end: break
y = process(x)
if y.is_what_we_are_looking_for():
_flag = 1
break
if not _flag:
raise "not found"
del _flag
This is a lot of verbage that does not say directly what we intend to do.
Huaiyu
More information about the Python-list
mailing list