Nested class doesn't see class scope

Ian Kelly ian.g.kelly at gmail.com
Tue Jul 5 00:41:16 EDT 2016


On Mon, Jul 4, 2016 at 9:20 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> I got this in Python 3.6:
>
>
> py> class A:
> ...     var = 999
> ...     print(var)  # succeeds
> ...     class B:
> ...         x = var
> ...
> 999
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 3, in A
>   File "<stdin>", line 4, in B
> NameError: name 'var' is not defined
>
>
> I expected that `var` would be available during the construction of B, just
> as it was available inside A, but not to methods inside B. Obviously my
> expectations are invalid. Can anyone explain the actual behaviour?

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.



More information about the Python-list mailing list