[Python-Dev] Informal educator feedback on PEP 572 (was Re: 2018 Python Language Summit coverage, last part)

Terry Reedy tjreedy at udel.edu
Thu Jun 28 13:18:36 EDT 2018

On 6/28/2018 8:05 AM, Baptiste Carvello wrote:
> Le 28/06/2018 à 01:31, Greg Ewing a écrit :
>> Well, I remain profoundly unconvinced that writing comprehensions
>> with side effects is ever a good idea, and Tim's examples did
>> nothing to change that.
> Comprehensions with side effects feel scary indeed. But I could see
> myself using some variant of the "cumsum" example (for scientific work
> at the command prompt):
>>>> x=0; [x:=x+i for i in range(5)]

Creating an unneeded list with a comprehension purely for side effects 
is considered a bad idea by many.

x = 0
for i in range(5): x += i

> Here the side effects are irrelevant, the "x" variable won't be reused.

If we ignore the side effect on x, the above is equivalent to 'pass' ;-)

Perhaps you meant

x = 0
cum = [x:=x+i for i in range(5)]

which is equivalent to

x, cum = 0, []
for i in range(5): x += i; cum.append(x)

> But it needs to be initialized at the start of the comprehension.
> I would happily get rid of the side-effects, but then what would be a
> non-cryptic alternative to the above example?

The above as likely intended can also be written

import itertools as it
cum = list(it.accumulate(range(5)))

We have two good existing alternatives to the proposed innovation.

Terry Jan Reedy

More information about the Python-Dev mailing list