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

Nick Coghlan report at bugs.python.org
Sun Oct 20 08:45:48 EDT 2019


Nick Coghlan <ncoghlan at gmail.com> added the comment:

The benefit offered by the parent local scoping was that it made assignment expressions usable as a straightforward way to implement comprehension-based accumulators where you actually do want access to the final value after the comprehension completes (for example, pulling the example or counter-example out of a call to any() or all()).

The downside is that you need an explicit "del j" after the comprehension to ensure prompt cleanup in those cases where you *don't* need the temporary variable after the comprehension has finished running:

    >>> [(j:=i*i)+1/j for i in range(1, 3)]; del j # Clean up temp

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

    [j+1/j for i in range(1, 3) for j in [i*i]]

So even with the parent local scoping semantics, PEP 572 is still enough to make Yury's comment above still hold (i.e. the use case is too obscure to justify the extra code needed to optimise it)

----------

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


More information about the Python-bugs-list mailing list