Fix Python – Accessing class variables from a list comprehension in the class definition

How do you access other class variables from a list comprehension within the class definition? The following works in Python 2 but fails in Python 3:
class Foo:
x = 5
y = [x for i in range(1)]

Python 3.2 gives the error:
NameError: global name ‘x’ is not defined

Trying Foo.x doesn’t work either. Any ideas on how to do this in Python 3?….

Fix Python – Scoping in Python ‘for’ loops

I’m not asking about Python’s scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were made in this way. For example (no pun intended):
for foo in xrange(10):
bar = 2
print(foo, bar)

The above will print (9,2).
This strikes me as weird: ‘foo’ is really just controlling the loop….

Fix Python – What’s the scope of a variable initialized in an if statement?

I’m new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly:
if __name__ == ‘__main__’:
x = 1

print x

In other languages I’ve worked in, this code would throw an exception, as the x variable is local to the if statement and should not exist outside of it. But this co….