[Python-Dev] The `for y in [x]` idiom in comprehensions

Paul Moore p.f.moore at gmail.com
Fri Feb 23 04:32:14 EST 2018


On 23 February 2018 at 09:12, Stefan Behnel <stefan_ml at behnel.de> wrote:
> Stephen J. Turnbull schrieb am 23.02.2018 um 03:31:
>> Barry Warsaw writes:
>>  > rather than having to pause to reason about what that 1-element
>>  > list-like syntax actually means, and 2) will this encourage even
>>  > more complicated comprehensions that are less readable than just
>>  > expanding the code into a for-loop?
>>
>> Of course it will encourage more complicated comprehensions, and we
>> know that complexity is less readable.  On the other hand, a for loop
>> with a temporary variable will take up at least 3 statements vs. a
>> one-statement comprehension.
>
> IMHO, any complex comprehension should be split across multiple lines,
> definitely if it uses multiple for-loops, as in the discussed example. So
> the "space win" of a complex comprehension that requires temporary values
> over a multi-line for-statement is actually not big in these cases.
>
> There are certainly cases where a comprehension still looks better, but I'm
> all for not encouraging a hacky idiom to stuff more into a comprehension.
> Comprehensions should be used to *improve* readabilty, not to reduce it.

In my view:

1. The proposal is for an optimisation, not a change to the language.
So anything bad that can be done after the change, can be done now.
2. I doubt many people avoid this construct at the moment because it's
slow, it's more likely they do so because they hadn't thought of it,
or because it harms readability.
3. Announcing that this construct is no longer slow might encourage
some extra people to use it (because they now know about it, and they
assume that the fact that we've optimised it implies we think it's a
good idea).
4. Ultimately, readability will be the main factor here. And
readability is subjective, so we sort of have to trust people to use
their common sense.

This could easily be a premature optimisation. But on the other hand,
it's a case of not making things unexpectedly slow, so I'm fine with
that.

If Serihy doesn't feel that the optimisation code is a major
maintenance burden, I'd say go for it. It's a minor quality of life
improvement for a niche case, let's not view (or promote) it as
anything more than that.

Paul


More information about the Python-Dev mailing list