Friday, August 27, 2010

Python: Comprehension loop variables

Python3 adds the nonlocal keyword, and alters list comprehensions to make their variables behave more like those in generator comprehensions.
"... the loop control variables are no longer leaked into the surrounding scope."
 Consider the following:




from __future__ import print_function

global x
x = 7

def main():
    x = 5
    def foo():
        #nonlocal x
        print("x =", x)
        return x

    foo()
    print([x for x in range(2)])
    print([foo() for x in range(2)])
    print(x)
    foo()

main()
 Python2.7 prints:


x = 5
[0, 1]
x = 0
x = 1
[0, 1]
1
x = 1

Python3.1 prints:


x = 5
[0, 1]
x = 5
x = 5
[5, 5]
5
x = 5

In other words, in Python2.7 list comprehension loop variables are part of the current scope, while Python3.1 they hide the scope, but only within the comprehension.  There is not really a lexical scope inside the comprehension.  It's a subtle distinction.

No comments:

Post a Comment