I\'m trying to perform some analysis of scope in Python 3 source code and I\'m stuck with how the nonlocal statement statement works inside a class definition.
As I
Lexical scoping applies only to function namespaces, otherwise methods defined inside a class would be able to "see" the class level attributes (which is by design - those attributes must instead be accessed as attributes of self
inside the method).
The same limitations that cause the class level variables to be skipped over by references from methods also keep the nonlocal
keyword from working its magic. (global
does work though, since that doesn't rely on the lexical scoping machinery)
Python handles class and function definitions rather differently. For example, your A.v
is not a variable of A but rather an attribute of it. The namespace created by a class is not, therefore, a scope. I am not surprised that nonlocal
does not work as you're trying to use it.