Given the following code:
a = 0
def foo():
# global a
a += 1
foo()
When run, Python complains: UnboundLocalError: local variable ‘a’ referenced before assignment
However, when it’s a dictionary…
a = {}
def foo():
a['bar'] = 0
foo()
The thing runs just fine…
Anyone know why we can reference a in the 2nd chunk of code, but not the 1st?
The difference is that in the first example you are assigning to
awhich creates a new local nameathat hides the globala.In the second example you are not making an assignment to
aso the globalais used.This is covered in the documentation.