On 23 June 2018 at 09:06, Greg Ewing email@example.com wrote:
Nick Coghlan wrote:
x:= f():" implies "x" is already defined as a target somewhere else in the current scope, while "if x := f() given x:" potentially introduces "x" as a new local target
Noooo..... this is just taking a bad idea and making it worse, IMO.
I'm -1 on any contortions designed to allow comprehensions to assign to things in outer scopes. All the proposed use cases I've seen for this have not improved readability over writing a function that does things the usual way.
Can we please leave comprehensions as declarative constructs? The best tools do just one thing and do it well. These proposals seem to be trying to turn comprehensions into swiss army knives.
If PEP 572 was proposing the use of regular local scoping for assignment expressions in comprehensions, such that they could still be used to avoiding repeating subexpressions within an iteration, but couldn't be used to export progress data, or to maintain a partial sum without having to rely on `locals().get("total", 0)` to provide an initial value, then I wouldn't be feeling obliged to present an alternative that offers the same state export capabilities in a more explicit form.
Given that PEP 572 *is* proposing implicit comprehension state export, though, then I think it's important to make the case that seeing the proposed semantics as intuitive is only going to be the case for folks that have used Python 2 style comprehensions extensively - anyone that's never encountered the old state-leaking behaviour for iteration variables is going to be surprised when assignment expressions ignore the existence of the comprehension scope (even though the iteration variable pays attention to it).