Is this a python bug? Or is my understanding of the name scope wrong?
The following example uses set comprehension in the class scope:
#/usr/bin/env python
class Foo(object):
xlist = 1,2,3,4,5,6,7,8
xset = {xlist[idx] for idx in range(0, len(xlist), 2)}
This example raises the error
Traceback (most recent call last):
File "./scope.py", line 2, in <module>
class Foo(object):
File "./scope.py", line 4, in Foo
xset = {xlist[idx] for idx in range(0, len(xlist), 2)}
File "./scope.py", line 4, in <setcomp>
xset = {xlist[idx] for idx in range(0, len(xlist), 2)}
NameError: global name 'xlist' is not defined
However, the following two codes do not raise any exception:
#/usr/bin/env python
class Foo(object):
xlist = 1,2,3,4,5,6,7,8
xset = {idx for idx in range(0, len(xlist), 2)}
#/usr/bin/env python
class Foo(object):
xlist = 1,2,3,4,5,6,7,8
xset = [xlist[idx] for idx in range(0, len(xlist), 2)]
Why does python fail to recognize the first "xlist" while it recognizes the second "xlist" in the last line of the first example? Since pythion can recognize the "xlist" in the other two examples. Even the "xlist" in list comprehension can be recognized, but the "xlist" in set comprehension can not be recognized? Seems the name scope of list comprehension and set comprehension is different?
By the way, my python version is 2.7.6.