[issue32856] Optimize the `for y in [x]` idiom in comprehensions

Serhiy Storchaka report at bugs.python.org
Sat Nov 16 12:20:06 EST 2019


Serhiy Storchaka <storchaka+cpython at gmail.com> added the comment:

> However, that's still going to be clearer to most readers than writing

It is subjective. To me, j+1/j looks clearer than (j:=i*i)+1/j. In addition, the for-as-assignment idiom is more powerful in context of comprehensions, it allows to set an initial value. In any case I want to have a choice.

> OOC, rather than optimizing a fairly ugly use case, might another approach be to make walrus less leaky?

I think this ship is sailed. The semantic of the walrus operator is complex enough to make it even more complex by adding more special cases. Also, while the function-wide optimization of variables is possible, it much more complex problem than the proposed simple optimization.

> You should probably rerun your benchmarks though

$ ./python -m timeit -s 'a = list(range(1000))' -- '[y for x in a for y in [x]]'
Unpatched:  5000 loops, best of 5: 66.8 usec per loop
Patched:   10000 loops, best of 5: 21.5 usec per loop

$ ./python -m timeit -s 'a = list(range(1000))' -- '[x for x in a]'
20000 loops, best of 5: 17.8 usec per loop

Issue32925 reduce the difference, but it is still large (~12).

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32856>
_______________________________________


More information about the Python-bugs-list mailing list