Why doesn't eval of generator expression work with locals?

Peter Otten __peter__ at web.de
Wed Jan 28 15:06:01 EST 2009


Gabriel Genellina wrote:

>>>> L = list(n for n in [globals(),locals()])
>>>> L[0] is L[1]
> True
>>>> L = list(n() for n in [globals,locals])
>>>> L[0] is L[1]
> False
> 
> (I think this has to do with free variables in the "right side" (after
> the "in" keyword) of a generator expression; they appear to be evaluated
> when the expression is *defined*, not when is is *used*. By contrast, free
> variables in the "left side" appear to be evaluated when the expression is
> used.)

Indeed, the right side is evaluated in the enclosing namespace and then
passed as an argument to the genexpr:

 >>> dis.dis(compile("(x for y in z)", "nofile", "exec"))
  1           0 LOAD_CONST               0 (<code object <genexpr> at
0x2b22b2dcf828, file "nofile", line 1>)
              3 MAKE_FUNCTION            0
              6 LOAD_NAME                0 (z)
              9 GET_ITER
             10 CALL_FUNCTION            1
             13 POP_TOP
             14 LOAD_CONST               1 (None)
             17 RETURN_VALUE


Peter



More information about the Python-list mailing list