[Python-Dev] Informal educator feedback on PEP 572 (was Re: 2018 Python Language Summit coverage, last part)
Terry Reedy
tjreedy at udel.edu
Sat Jun 30 16:06:39 EDT 2018
On 6/30/2018 5:35 AM, Steven D'Aprano wrote:
> I've given reasons why I believe that people will expect assignments in
> comprehensions to occur in the local scope. Aside from the special case
> of loop variables, people don't think of comprehensions as a separate
> scope.
I think this is because comprehensions other than generator expressions
were originally *defined* in terms of equivalent code in the *same*
local scope, are still easily thought of in those terms, and, as I
explained in my response to Guido, could, at least in simple cases,
still be implemented in the local scope, so that assignment expressions
would be executed and affect the expected local scope without 'nonlocal'.
Generator expressions, on the other hand, have always been defined in
terms of equivalent code in a *nested* scope, and must be implemented
that way, so some re-definition and re-implementation is needed for
assignment expressions to affect the local scope in which the g.e is
defined and for that effect to be comprehensible. It might be enough to
add something like "any names that are targets of assignment expressions
are added to global or nonlocal declarations within the implementation
generator function."
If the equality [generator-expression] == list(generator-expression] is
preserved, then it could serve as the definition of the list
comprehension. The same could be true for set and dict comprehensions,
with the understanding that the equality is modified to {a:b for ...} ==
dict((a,b) for ...). It should also be mentioned that the defining
equality is not necessarily the implementation.
--
Terry Jan Reedy
More information about the Python-Dev
mailing list