I seem to be unsure as to how Python deals with variable scope in classes. This simple class demonstrates my issue:
x = 5 # Outside class scope
class SomeClass:
x = 17 # Inside class scope
# Generator expression should use x = 17 from inside class scope
y = (x for i in range(10))
Output:
>>> list(SomeClass.y)
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
Apparently, the generator expression ignored the x = 17
from inside the class. So, I thought I would change it to a list comprehension:
x = 5 # Outside class scope
class SomeClass:
x = 17 # Inside class scope
# List expression should use x = 17 from inside class scope
y = [x for i in range(10)]
Output (Python 2.x):
>>> SomeClass.y
[17, 17, 17, 17, 17, 17, 17, 17, 17, 17]
In Python 2.x, list comprehensions seem to use the class's scope. However, this is not true in Python 3.x:
Output (Python 3.x):
>>> SomeClass.y
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
If I am to use Python 3.x, how do I use the class's variable scope? Both generator and list comprehensions seem to fail in using the class scope.