On 8/10/2017 10:28 AM, Steve D'Aprano wrote:
Every few years, the following syntax comes up for discussion, with some people
saying it isn't obvious what it would do, and others disagreeing and saying
that it is obvious. So I thought I'd do an informal survey.
What would you expect this syntax to return?
[x + 1 for x in (0, 1, 2, 999, 3, 4) while x < 5]
I expect it to continue to raise SyntaxError as I would be flabbergasted
if something so awful were to be accepted into Python.
If it were were to mean what it 'obviously' should, by analogy with the
current meaning and translation
val = []
for x in (0, 1, 2, 999, 3, 4):
while x < 5:
val.append(x)
then it would 'mean' an infinite list of, in this case, 1's, and raise
OutOfMemoryError. This is, of course, useless. Better to leave it as a
SyntaxError.
If 'while cond' were to not mean 'conditionally loop', but, as some
want, 'conditionally break an existing loop', something like 'if not
cond: break', it would mean 'Python is really confusing and
inconsistent'. It would be terrible to have a keyword with two such
related but opposite meanings.
Better to allow people to say what they mean, something like 'if cond
break'. A 'semi-obvious' translations might then be
val = []
it = iter((0, 1, 2, 999, 3, 4))
for x in it:
if x < 5:
val.append(x+1)
else:
break
val = [1,2,3]
Notice that this consumes one item in iterator it without processing it.
A likely source of bugs if one intends to resume use of it.
I believe some want to add to the confusion by breaking more rules of
comprehension interpretation by translating to something like
val = []
it = iter((0, 1, 2, 999, 3, 4))
for x in it:
val.append(x+1)
if x >= 5:
break
val = [1,2,3,100]
This has the opposite potential bug of including the stop value.
Summary: If 'while cond' in comprehensions were no longer a SyntaxError,
I would expect unending confusion and ultimately regret.
--
Terry Jan Reedy
--
https://mail.python.org/mailman/listinfo/python-list