[Python-ideas] A comprehension scope issue in PEP 572

Nick Coghlan ncoghlan at gmail.com
Sun May 6 23:11:48 EDT 2018


On 7 May 2018 at 12:51, Nick Coghlan <ncoghlan at gmail.com> wrote:

> If any other form of comprehension level name binding does eventually get
> accepted, then inline scope declarations could similarly be used to hoist
> values out into the surrounding scope:
>
>         rem = None
>         while any((nonlocal rem := n % p) for nonlocal p in small_primes):
>             # p and rem were declared as nonlocal in the nested scope, so
> our rem and p point to the last bound value
>

Thinking about it a little further, I suspect the parser would reject
"nonlocal name := ..." as creating a parsing ambiguity at statement level
(where it would conflict with the regular nonlocal declaration statement).

The extra keyword in the given clause would avoid that ambiguity problem:

        p = rem = None
        while any(rem for nonlocal p in small_primes given nonlocal rem = n
% p):
            # p and rem were declared as nonlocal in the nested scope, so
our p and rem refer to their last bound values

Such a feature could also be used to make augmented assignments do
something useful at comprehension scope:

    input_tally = 0
    process_inputs(x for x in input_iter given nonlocal input_tally += x)

Cheers,
Nick.

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


More information about the Python-ideas mailing list