Proposed new syntax
Ian Kelly
ian.g.kelly at gmail.com
Thu Aug 10 16:28:50 EDT 2017
On Thu, Aug 10, 2017 at 1:49 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> 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]
So, perhaps a better syntax could be:
[x + 1 for x in (0, 1, 2, 999, 3, 4) if x < 5 else break]
More information about the Python-list
mailing list