[Python-ideas] A comprehension scope issue in PEP 572

Tim Peters tim.peters at gmail.com
Mon May 7 17:41:40 EDT 2018


[Terry Reedy <tjreedy at udel.edu>]
> ...
> If I am understanding correctly, this would also let one *intentionally
> 'leak' (export) the last value of the loop variable when wanted.
>
> [math.log(xlast:=x) for x in it if x > 0]
> print(xlast)

Yup!  You can do that today by emulating a nonlocal "cell" reference,
but I don't recommend it ;-)

    xlast_cell = [None]
    [math.log(x) for x in it if x > 0
                 for xlast_cell[0] in [x]]
    print(xlast_cell[0])


More information about the Python-ideas mailing list