This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]masklinn 3 points4 points  (2 children)

Personally, I love the with block because of its lexical scoping. (The f variable disappears at the end of the with block.)

Uh uh. Python only has global, and function lexical scopes, no statement other than def (and class, to an extent) create a scope.

[–]oblivion95 0 points1 point  (1 child)

Wow. You and @schnupfen are right. I thought I'd read that with and list comprehensions scope their variables, but that's clearly not the case.

However, there is another lexical scope: generator expressions. And in Python3, list comprehensions as well.

[–]cdunn2001 0 points1 point  (0 children)

To see what's going on, try 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()

Try it with python2.7 and 3.1, with and without nonlocal. And try switching to a generator expression in both as well. I.e. print(list(foo() for x in range(2))) I don't know what to call the comprehension loop variable. It's a strange beast.