This is a question purely regarding language mechanics, not best practice. I'm mainly interested in python 3.
Suppose we have the following:
x = 5
def foo():
return x + 1 # Succeeds
def foo2():
x = x + 1
return x # Fails
class Bar(object):
x = x + 1 # Succeeds, Why?
def some_method(self):
return x
bar_instance = Bar()
It's well known that calling foo() will succeed as x will be retrieved from the global scope.
It's also well known foo2() will fail with an UnboundLocalError since the presence of x on the left of the assignment creates a local variable masking the global, which will cause the expression on the right side to fail. This is a bit unintuitive (I'd expect the local x to be initialized from the global x) but I understand the mechanics behind it.
Class Bar however, will initialize successfully. It creates a class-scope variable and initializes from the global, which is exactly what I'd expect. While this is nice, it's a bit incongruous to me. Why doesn't it run into the same masking issues as is the case with foo2()? Is there some magic in the class scope that it gets for existing outside of the typical LEGB scope hierarchy?