I've come across some very odd handling of global variables in Python. I was hoping someone can explain and justify these surprises!
A) This code prints 10 as expected:
def func():
print(a)
a = 10
func()
B) This code throws an exception about referencing a too early:
def func():
print(a)
a += 1
a = 10
func()
C) But this code prints [10] as expected:
def func():
print(a)
a.append(1)
a = [10]
func()
So I can gather that the type of a changes its scope and additionally later statements that haven't even been reached yet change how a is seen. I know I can use global a at the start of the function but it's rather verbose.
Can anyone tell me what rules Python is using to handle its bizarre scoping?
globals you should probably reconsider your design. Functions are nicer when they accept parameters to mutate or even better(usually), return the new version without mutating the original. In your last example you are not even binding the nameato a different value as @Ignacio said. You are simply accessing a method ofaso that shouldn't be a surprise.achange the meaning between a variable of a parent scope and local scope is quite confusing I think and not very consistent. It's either a local variable, or not. Never both.