I am seeing an error when assigning either a global or an enclosing-function local to a local variable with the same name. The code below illustrates this issue, where f() runs fine, while g() raises an error. It seems like python knows that a is being assigned locally, so it says that all references to a are now local, even the references before a is actually assigned locally. What explains this behavior? I am running Python 2.7.12 :: Anaconda 4.2.0 (64-bit).
In [18]: a = 1
...:
...: def f():
...: x = a
...: print x
...:
...: def g():
...: a = a
...: print a
...:
In [19]: f()
1
In [20]: g()
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-20-d65ffd94a45c> in <module>()
----> 1 g()
<ipython-input-18-f3d970bdaa2b> in g()
6
7 def g():
----> 8 a = a
9 print a
10
UnboundLocalError: local variable 'a' referenced before assignment