Odd name shadowing in comprehension

eryk sun eryksun at gmail.com
Sun Oct 23 01:08:01 EDT 2016


On Sun, Oct 23, 2016 at 3:44 AM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
>
> https://www.python.org/dev/peps/pep-0289/#early-binding-versus-late-binding
>
> But this isn't a question about early or late binding, it is asking why the
> variable y is treated as both global and local in the same comprehension.
> This may be an unexpected side-effect of other choices, but I don't see any
> discussion or consideration of this specific issue.

For generator expressions, it's about early binding of the outer
iterator. This makes the result of the expression for the outer
iterator behave like a function parameter. Obviously it has to be
evaluated in the defining scope. Comprehensions have adopted the same
behavior, and it's not a bug or a flawed design. However it does need
to be documented better in section 6.2.4.

If the expression for the outer iterator is `range(y)`, the compiler
emits whatever operation is required to load y in the defining scope.
At the module or class level it emits a LOAD_NAME. At function scope,
it uses LOAD_FAST when y is local, LOAD_DEREF when y is a free
variable, and otherwise LOAD_GLOBAL. The interpreter evaluates the
expression (e.g. it calls range) and executes GET_ITER on the result.
The resulting iterator is passed as parameter ".0" to the [generator]
function that implements the comprehension or generator expression.



More information about the Python-list mailing list