[Python-Dev] PEP 572: Assignment Expressions

Anthony Flury anthony.flury at btinternet.com
Sat Apr 21 04:38:04 EDT 2018


On 21/04/18 08:46, Chris Angelico wrote:
> doubled_items = [x for x in (items := get_items()) if x * 2 in items]
>
> This will leak 'items' into the surrounding scope (but not 'x').
At the risk of stating the obvious - wasn't there work in Python 3 to 
prevent leakage from comprehensions ?
> [x for x in x if x] # This works
> [x for y in x if x := y] # UnboundLocalError

The standard library example given earlier notwithstanding, I can see no 
benefit in using the same name as the iterator and the loop target name. 
To be honest I have trouble parsing that first version, and keeping 
track of which x is which (especially which x is being used in the 
conditional clause) : surely this would be better : [x_item for x_item 
in x if x_item]

Your 2nd example makes no sense to me as to the intention of the code - 
the re-use of the name x is confusing at best.


-- 
Anthony Flury
email : *Anthony.flury at btinternet.com*
Twitter : *@TonyFlury <https://twitter.com/TonyFlury/>*



More information about the Python-Dev mailing list