As you may know, the scope of a variable is statically determined in python (What are the rules for local and global variables in Python?).
For instance :
a = "global" def function(): print(a) a = "local" function() # UnboundLocalError: local variable 'a' referenced before assignment The same rule applies to classes, but it seems to default to the global scope instead of raising an AttributeError:
a = "global" class C(): print(a) a = "local" # 'global' Moreover, in the case of a nested function, the behavior is the same (without using nonlocal or global) :
a = "global" def outer_func(): a = "outer" def inner_func(): print(a) a = "local" inner_func() outer_func() # UnboundLocalError: local variable 'a' referenced before assignment But in the case of nested classes, it still defaults to the global scope, and not the outer scope (again without using global or nonlocal) :
a = "global" def outer_func(): a = "outer" class InnerClass: print(a) a = "local" outer_func() # 'global' The weirdest part is that the nested class default to the outer scope when there is no declaration of a :
a = "global" def outer_func(): a = "outer" class InnerClass: print(a) outer_func() # 'outer' So my questions are :
- Why the discrepancy between functions and classes (one raising an exception, the other defaulting to the global scope.
- In nested classes, why the default scope has to become global instead of keeping using the outer one when using a variable defined afterward?