Name lookup at class scope is weird and not really consistent with its documentation.
Normally, unlike with a function scope, name lookup in a class scope happens the same regardless of whether the scope has assignments to the name; locals first, then globals, then builtins. However, nonlocal lookup in a class scope is affected by assignments in that class scope.
If you do something like
def classMaker(x):
class y(object):
z=x # not x=x
return y
Python sees that the name x
matches a nonlocal variable, and it uses the LOAD_DEREF
opcode to access the closure cell for that variable. However, the assignment to x
in your actual code:
def classMaker(x):
class y(object):
x=x
return y
causes Python to use LOAD_NAME
, the usual opcode for class-scope name lookup, which doesn't see closure variables.