Categories
Programming

python list comprehensions, with surprise!

Wasn’t expecting this behavior, but variables used in list comprehensions and with blocks continue to be in scope…

# variables introduced in list comprehensions continue to exist in scope
[a_var for a_var in range(10)]

print "Hey, what's a_var?", a_var

# similar thing happens when using "with"
with open("some_file.txt") as a_file:
    pass

print "Hey, what's a_file?", a_file
python test.py
Hey, what's a_var? 9
Hey, what's a_file? <closed file 'some_file.txt', mode 'r' at 0xb747cee8>

Leave a Reply