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

Nick Coghlan ncoghlan at gmail.com
Mon May 14 09:13:26 EDT 2018

On 14 May 2018 at 06:10, Tim Peters <tim.peters at gmail.com> wrote:

> [Greg Ewing <greg.ewing at canterbury.ac.nz>']
> > This whole discussion started because someone wanted a way
> > to bind a temporary result for use *within* a comprehension.
> It's been noted several times recently that the example PEP 572 gives
> as _not_ working:
>     total = 0
>     progressive_sums = [total := total + value for value in data]
> was the original use case that prompted work on the PEP.  You gotta
> admit that's ironic ;-)

After pondering this case further, I think it's also worth noting that that
*particular* example could also be addressed by:

1. Allowing augmented assignment *expressions*
2. Changing the scoping rules for augmented assignment operations in
general such that they *don't change the scope of the referenced name*

Writing "i += n" without first declaring the scope of "i" with "i = 0",
"nonlocal i" or "global i" is one of the most common sources of
UnboundLocalError after all, so I'd be surprised to find anyone that
considered the current augmented assignment scoping rules to be outside the
realm of reconsideration.

The accumulation example would then be written:

    total = 0
    progressive_sums = [total += value for value in data]
    if progressive_sums:
        assert total == progressive_sums[-1]

The question would then turn to "What if you just want to bind the target
name, without considering the old value?". And then *that's* where "NAME :
= EXPR" would come in: as an augmented assignment operator that used
augmented assignment scoping semantics, rather than regular local name
binding semantics.

That would mean *directly* overturning PEP 3099's rejection of the idea of
using "NAME := EXPR" to imply "nonlocal NAME" at function scope, but that's
effectively on the table for implicit functions anyway (and I'd prefer to
have ":=" be consistent everywhere, rather than having to special case the
implicit scopes).


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180514/eea30f1b/attachment-0001.html>

More information about the Python-ideas mailing list