Have a look at this simple Python code:
class A:
x = 123
y = [(x,x*x) for x in [1,2,3]]
print A().x
A.x
is 123
, but when I do A().x
, it prints 3
. Why?
$ python a.py
3
Have a look at this simple Python code:
class A:
x = 123
y = [(x,x*x) for x in [1,2,3]]
print A().x
A.x
is 123
, but when I do A().x
, it prints 3
. Why?
$ python a.py
3
It's a behaviour related to py2.x. In py2.x the list comprehensions don't have their own scope. So, the list comprehension in your case actually modified the variable x
and as x
was assigned the value 3
at the end of list comprehension so you'll get 3
for both A().x
and A.x
.
...and in particular the loop control variables are no longer leaked into the surrounding scope.
You have overriden the x
in the list comprehension. Should use another name.