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

Tim Peters tim.peters at gmail.com
Mon May 7 15:21:26 EDT 2018


[Tim]
> While I don't have real use cases beyond that, given that much,
> "consistency" kicks in to suggest that:
>
>     def f():
>          [x := 42 for x in range(1)]
>
> makes `x` local to `f` despite that x wasn't bound elsewhere in f's body.
>
>     def f():
>         global x
>          [x := 42 for x in range(1)]
>
> binds the global `x`.
>
>     def f():
>         nonlocal x
>          [x := 42 for x in range(1)]
>
> binds `x` in the closest-containing scope in which `x` is local.  The
> last two act as if the declaration of `x` in `f` were duplicated at
> the start of the synthetic function.
>
> More succinctly, that `x := RHS` in a synthetic function "act the
> same" as `x = RHS` appearing in the scope directly containing the
> synthetic function.

Oh, fudge - I wasn't trying to make a silly subtle point by reusing
`x` as the `for` variable too.  Pretend those all said "for i in
range(1)" instead.  Of course what happens if `x` is used in both
places needs to be defined, but that's entirely beside the intended
point _here_.


More information about the Python-ideas mailing list