3
a=0
b=1
class A:
    a=42
    b=list((a,a+1,a+2))
x=A()
print(x.b)

output: [42, 43, 44]

VS

a=0
b=1
class A:
    a=42
    b=list((a+i for i in range(3)))
x=A()
print(x.b)

output: [0, 1, 2]

So in the first example, a=42 was used. But in the second example, a=0 was used. Why is that so?

Qingwan Kuah
  • 261
  • 2
  • 6
  • This is an interesting problem whose *real* solution is "stop shadowing variable names." I'm looking forward to someone explaining the internals (which I thought were related to the latter being a genexp, but doesn't appear to be) – Adam Smith Apr 11 '18 at 04:43

1 Answers1

0

Ok, I found this reasoning in my professor's slides:

"The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods - this includes comprehensions and generator expressions since they are implemented using a function scope." - Dr. Zhao Yibao

so in example 2, list((a+i for i in range(3))) is an example of a list comprehension. Hence, it takes the global namespace a=0. It does not recognize a=42 as that was defined in the class block, A().

Hope someone can vet my reasoning, I'm not sure if it's entirely correct.

Qingwan Kuah
  • 261
  • 2
  • 6