"... the loop control variables are no longer leaked into the surrounding scope."Consider the following:
Python2.7 prints:
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()
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