Eryk Sun added the comment: The class example defines "i" as a local variable, which means the CPython operation used for unoptimized code (class or module/exec) is LOAD_NAME, which searches locals, globals, and builtins. The result differs from the exec example because a class is executed with a new locals dict to capture the class namespace.
I think a more interesting case to explain is code that uses LOAD_CLASSDEREF. This operation tries locals and nonlocals, but not globals or builtins. i = 'global' def f(): i = 'nonlocal' class C: print(i) >>> f() nonlocal i = 'global' def f(): class C: print(i) i = 'nonlocal' >>> f() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f File "<stdin>", line 3, in C NameError: free variable 'i' referenced before assignment in enclosing scope i = 'global' def f(): class C: locals()['i'] = 'local' print(i) i = 'nonlocal' >>> f() local i = 'global' def f(): i = 'nonlocal' class C: nonlocal i print(i) i = 'new nonlocal' print(i) print(i) >>> f() nonlocal new nonlocal new nonlocal ---------- nosy: +eryksun _______________________________________ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue26225> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com