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

Chris Angelico rosuav at gmail.com
Sun May 6 22:48:53 EDT 2018


On Mon, May 7, 2018 at 12:34 PM, Tim Peters <tim.peters at gmail.com> wrote:
>> That's a fair point. But there is another equally valid use-case for
>> assignment expressions inside list comps:
>>
>> values = [y + 2 for x in iter if (y := f(x)) > 0]
>>
>> In this case, it's just as obvious that the name 'y' should be local
>> to the comprehension, as 'x' is.
>
> There's a difference, though:  if `y` "leaks", BFD.  Who cares? ;-)
> If `y` remains inaccessible, there's no way around that.

That's Steve D'Aprano's view - why not just let them ALL leak? I don't
like it though.

>> 2) All names are local to their own scope. No names leak, and that
>> includes names made with ":=".
>
> Saying "local to their own scope" _assumes_ what you're trying to
> argue _for_ - it's circular.  In fact it's impossible to know what the
> user intends the scope to be.

Sorry, I meant "local to the comprehension's scope". We can't know the
user's intention. We have to create semantics before the user's
intention even exists.

> But the point above remains:  if they don't leak, contexts that want
> them to leak have no recourse.  If they do leak, then the other uses
> would still work fine, but they'd possibly be annoyed by a leak they
> didn't want.

Then let's revert the Py3 change that put comprehensions into
functions, and put them back to the vanilla transformation:

stuff = [x + 1 for x in iter if x % 3]

stuff = []
for x in iter:
    if x % 3:
        stuff.append(x + 1)

Now 'x' leaks as well, and it's more consistent with how people
explain comprehensions. Is that a good thing? I don't think so. Having
the iteration variable NOT leak means it's a self-contained unit that
simply says "that thing we're iterating over".

> Part of that is because - as the existence of this thread attests to -
> we can't even control all the scopes gimmicks Python already has.  So
> people are understandably terrified of adding even more ;-)

Part of it is just that people seem to be fighting for the sake of
fighting. I'm weary of it, and I'm not going to debate this point with
you. You want 'em to leak? No problem. Implement it that way and I'm
not going to argue it.

ChrisA


More information about the Python-ideas mailing list