The question is one of update.
You cannot update a
because it is not a variable in your function's local namespace. The update-in-place assignment operation fails to update a
in place.
Interestingly, a = a + 1
also fails.
Python generates slightly optimized code for these kind of statements. It uses a "LOAD_FAST" instruction.
2 0 LOAD_FAST 0 (a)
3 LOAD_CONST 1 (1)
6 INPLACE_ADD
7 STORE_FAST 0 (a)
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
Note that the use of a
on left and right side of the equal sign leads to this optimization.
You can, however, access a
because Python will search local and global namespaces for you.
Since a
does not appear on the left side of an assignment statement, a different kind of access is used, "LOAD_GLOBAL".
2 0 LOAD_CONST 1 (0)
3 LOAD_GLOBAL 0 (a)
6 LOAD_CONST 2 ('bar')
9 STORE_SUBSCR
10 LOAD_CONST 0 (None)
13 RETURN_VALUE