On 26 May 2018 at 04:14, Tim Peters firstname.lastname@example.org wrote:
... We could use given for both the in-loop variable update and the variable initialization: smooth_signal = [average given average=(1-decay)*average + decay*x for x in signal] given average=0.
[Steven D'Aprano email@example.com]
I don't think that will work under Nick's proposal, as Nick does not want assignments inside the comprehension to be local to the surrounding scope. (Nick, please correct me if I'm wrong.)
Nick appears to have moved on from "given" to more-general augmented assignment expressions.
Aye, while I still don't want comprehensions to implicitly create new locals in their parent scope, I've come around on the utility of letting inline assignment targets be implicitly nonlocal references to the nearest block scope.
See PEP 577, but note that it's still a work-in-progress:
Under that PEP,
average = 0 smooth_signal = [(average := (1-decay)*average + decay*x) for x in signal]
Or, for the running sums example:
total = 0 sums = [(total += x) for x in data]
I'm not entirely clear on whether the "extra" parens are needed, so added 'em anyway to make grouping clear.
I think the parens would technically be optional (as in PEP 572), since "EXPR for" isn't legal syntax outside parentheses/brackets/braces, so the parser would terminate the assignment expression when it sees the "for" keyword.