Nested class doesn't see class scope

eryk sun eryksun at gmail.com
Tue Jul 5 08:45:41 EDT 2016


On Tue, Jul 5, 2016 at 5:40 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Tuesday 05 July 2016 14:41, Ian Kelly wrote:
>
>> Class definitions don't create closures like functions do. When Python
>> executes a class definition, the metaclass creates a dict, and then
>> the interpreter execs the class body using that dict as the locals.
>> The body of class A has one locals dict, and the body of class B has a
>> completely separate locals dict. The only way to share variables
>> between them (prior to the class objects actually being constructed)
>> is via globals.
>
>
> So, like nested functions in Python before "from __future__ import
> nested_scopes".

In Python 3.4+, the code for a class body does participate in
closures. The CPython compiler implements this using the
LOAD_CLASSDEREF instruction. However, classes don't create closures
and default to storing to the locals dict (as class attributes),
unless a name is declared global or nonlocal. Obviously writing to a
global or nonlocal won't create a class attribute. For example:

    def f():
        y = 0
        class C:
            global x
            nonlocal y
            x = 1
            y = 2
            z = 3
        return types.SimpleNamespace(**locals())

    >>> ns = f()
    >>> x
    1
    >>> ns.y
    2
    >>> ns.C.z
    3
    >>> sorted(vars(ns.C))
    ['__dict__', '__doc__', '__module__', '__weakref__', 'z']



More information about the Python-list mailing list