[docs] [issue26225] New misleading wording in execution model documenation

Eryk Sun report at bugs.python.org
Wed Jan 27 20:29:15 EST 2016


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 <report at bugs.python.org>
<http://bugs.python.org/issue26225>
_______________________________________


More information about the docs mailing list