[Python-ideas] Inline assignments using "given" clauses

Tim Peters tim.peters at gmail.com
Sat May 12 14:13:05 EDT 2018


Just clarifying a fine point here:

[Steven D'Aprano <steve at pearwood.info>]
> ...
> average = 0
> smooth_signal = [(average := (1-decay)*average + decay*x) for x in signal]
> assert average == smooth_signal[-1]
>
> I'm not even sure if "given" will support this. Nick is arguing strongly
> that bound targets should be local to the comprehension, and so I think
> you can't even write this example at all with Nick's scoping rule.

You can't under Nick's proposal(s), at least not directly (there are
always "tricks").  But it also blows up with UnboundLocalError (for
the "average" in "(1-decay)*average") under the current PEP 572 (the
":=" PEP).

I've proposed to change 572's scoping rules for targets of assignment
expressions appearing in comprehensions so that "it would just work"
instead, but that's getting strong opposition too.  My favorite so far
was Nick's (Coghlan's) entertainingly hyperbolic:

    "Comprehension scopes are already confusing, so it's OK to dial their
    weirdness all the way up to 11" is an *incredibly* strange argument to be
    attempting

:-)

The scope issues are logically independent of assignment-expression
spelling, but it's a pretty safe guess Nick is opposed to that example
ever "just working" regardless of spelling, while PEP 572 doesn't
currently support it anyway.  Last I heard, Chris (Angelico - the
PEP's author) didn't seem keen on changing it either.


More information about the Python-ideas mailing list