[Python-ideas] PEP 572 version 2: Statement-Local Name Bindings

Chris Angelico rosuav at gmail.com
Sun Mar 25 06:13:56 EDT 2018


On Sun, Mar 25, 2018 at 8:31 PM, Christoph Groth
<christoph at grothesque.org> wrote:
> That's indeed a bit strange, and I would consider it somewhat of a wart
> of the language.  But as far as I can tell remaining compatible with the
> above behavior does not force us to leak assignments from the outermost
> scope of a comprehension.  I.e. there's nothing in the language
> currently that forces
>
> listcomp = [x for x in (r := sequence)]
>
> to leak the name "r".
>
> Granted, it's a bit strange if in the above line the name "sequence" is
> evaluated in class scope but the name "r" is set in the comprehension
> scope, but since currently there is no way to assign values to names in
> comprehensions this "hybrid" behavior would be backwards-compatible, and
> less surprising than leaking "r".

It seems fine in a simple example, but remember, an assignment
expression can be used ANYWHERE in an expression. Consider:

listcomp = [x for x in obj[r := f()][x + r] ]

Which parts happen in the inner scope and which in the outer scope? If
'r' is created in a subscope, it has to be a subscope of the outer
scope; if it's not subscoped, it has to be directly in the outer
scope. It can't sanely be in the inner scope.

ChrisA


More information about the Python-ideas mailing list