When referencing global variables, one can see that functions and classes handle this differently. The first is fine and the second causes an error:
x = 10
class Foo():
x = x + 1
a = foo()
Vs:
x = 10
def faa():
x = x + 1
faa()
In the Python execution model, this is described as:
A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace.
But why?
The only other hint I have come across is this bit:
The class’s suite is then executed in a new execution frame (see section Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains only function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. 4 A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary.
Which still offers no explanation why this should have the consequence that unbound locals are looked up in the global namespace.
Both links are from this answer which does not adress the why in more details though.