Message259083
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 |
|
Date |
User |
Action |
Args |
2016-01-28 01:29:15 | eryksun | set | recipients:
+ eryksun, docs@python, abarnert |
2016-01-28 01:29:15 | eryksun | set | messageid: <1453944555.49.0.579877434499.issue26225@psf.upfronthosting.co.za> |
2016-01-28 01:29:15 | eryksun | link | issue26225 messages |
2016-01-28 01:29:14 | eryksun | create | |
|