This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author eryksun
Recipients abarnert, docs@python, eryksun
Date 2016-01-28.01:29:14
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1453944555.49.0.579877434499.issue26225@psf.upfronthosting.co.za>
In-reply-to
Content
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
History
Date User Action Args
2016-01-28 01:29:15eryksunsetrecipients: + eryksun, docs@python, abarnert
2016-01-28 01:29:15eryksunsetmessageid: <1453944555.49.0.579877434499.issue26225@psf.upfronthosting.co.za>
2016-01-28 01:29:15eryksunlinkissue26225 messages
2016-01-28 01:29:14eryksuncreate