Question:
I made the two functions below in Python 3. The first functiontest_list
works fine with the list a
without error. I can modify the list element in that function.However, the second funciton
test_int
will pop an error local variable 'b' referenced before assignment
. Why can’t I do this to the variable b
?Answer:
b += 1
is equivalent to b = b.__iadd__(1)
; since the name b
gets bound by that statement (l.h.s.), the compiler infers that b
is a local variable; however, the r.h.s. expression contains the name b
as well and thus you get the error “local variable 'b'
referenced before assignment” (the local name b
doesn’t refer to anything at the time when the expression is evaluated).a[0] = 2
on the other hand is equivalent to a.__setitem__(0, 2)
and thus involves no name binding.If you wish to modify a global name binding within a function, you can use the keyword
global
; there’s also the equivalent nonlocal
for names contained in an outer, but not the global, scope.If you have better answer, please add a comment about this, thank you!