Ask for help about class variable scope (Re: Why doesn't a dictionary work in classes?)

eryk sun eryksun at
Thu Dec 27 05:58:17 EST 2018

On 12/27/18, jfong at <jfong at> wrote:
> I still don't get it. When I change it to using list comprehension, the
> problem is still there. (it now has no late-binding variable, right? :-)
>>>> class Too:
> ...     XS = [15, 15, 15, 15]
> ...     Z4 = [val for val in XS]
> ...     Z5 = [XS[0] for val in XS]
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 4, in Too
>   File "<stdin>", line 4, in <listcomp>
> NameError: name 'XS' is not defined
> The problem confuse me is that is XS a local variable of the list
> comprehension?

XS is not a local variable in the scope of either comprehension. XS is
local to the class statement's scope. For each comprehension, an
iterator for the current object referenced by XS gets instantiated
(early binding) and passed as an argument to the comprehension scope.
If we disassemble the comprehension code, we find that this iterator
argument has the creatively illegal name ".0". (The bytecode
references it by its fast-locals-array index, not its weird name.)

In the Z5 case, XS is a non-local variable (late binding) in the
loop-body expression (left-hand side) of the comprehension. That's
common for Python code. In every iteration of the loop, the
interpreter looks up the object referenced by the name "XS", which can
change at any time (e.g. by another thread).

More information about the Python-list mailing list