<div dir="ltr"><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div>So the way I envision it is that *in the absence of a nonlocal or global declaration in the containing scope*, := inside a comprehension or genexpr causes the compiler to assign to a local in the containing scope, which is elevated to a cell (if it isn't already). If there is an explicit nonlocal or global declaration in the containing scope, that is honored.<br><br></div>Examples:<br><br></div><div>  # Simplest case, neither nonlocal nor global declaration<br></div>  def foo():<br></div>      [p := q for q in range(10)]  # Creates foo-local variable p<br></div>      print(p)  # Prints 9<br><br></div><div>  # There's a nonlocal declaration<br></div>  def bar():<br></div><div>      p = 42  # Needed to determine its scope<br></div>      def inner():<br></div>          nonlocal p<br></div>          [p := q for q in range(10)]  # Assigns to p in bar's scope<br></div>      inner()<br></div>      print(p)  # Prints 9<br><br></div><div>  # There's a global declaration<br></div>  def baz():<br></div><div>      global p<br></div>      [p := q for q in range(10)]<br></div>  baz()<br></div>  print(p)  # Prints 9<br><br></div>All these would work the same way if you wrote list(p := q for q in range(10)) instead of the comprehension.<br><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><br></div><div>We should probably define what happens when you write [p := p for p in range(10)]. I propose that this overwrites the loop control variable rather than creating a second p in the containing scope -- either way it's probably a typo anyway.<br></div><div><br>:= outside a comprehension/genexpr is treated just like any other assignment (other than in-place assignment), i.e. it creates a local unless a nonlocal or global declaration exists.<br><div><br><div class="gmail_extra">-- <br><div class="gmail_signature" data-smartmail="gmail_signature">--Guido van Rossum (<a href="http://python.org/~guido" target="_blank">python.org/~guido</a>)</div>
</div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div>