1

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.

Suraj Kothari
  • 1,642
  • 13
  • 22
  • Is there a way to use the inner scope or will Python not allow it at all – Suraj Kothari Jan 27 '19 at 17:44
  • This won't work, because `list` comprehensions and generator expressions create a function scope. So just like in a method, you can't access variables in the class body without referencing them using the class namespace, but the class namespace *does not exist yet* when you are using the comprehension. This worked in Python 2 because list-comprehensions were implemented differently, leading to "leaky" scope. This was fixed later. Note, other comprehension constructs never worked that way – juanpa.arrivillaga Jan 27 '19 at 18:40

0 Answers0