I'm flummoxed by the following behavior in Python that I would like somebody to explain to me, if possible. I've reduced it to very simple code, to point down where the problem is:
This is the starter code:
def doSomething():
print (a)
a = 'hello'
doSomething()
As you'd expect, this prints 'hello' without much trouble. The variable a is outside of the function but nonetheless accessible given its of 'global scope'. So, let's just reassign it to something else, shall we?
def doSomething():
print (a)
a = 'goodbye'
a = 'hello'
doSomething()
Now, this blows up, telling me that the local variable 'a' was referenced before assignment in the print statement. This is odd, because the variable 'a' was present at the time of the print statement (as evidenced in the first code snippet, which worked well). So why is Python complaining now?
My hypothesis is that Python automagically and preemptively scans through the function code to see if there is a namespace conflict between global and local variables, and if so, it lets the local one win. So for the doSomething() function in the second code snippet, it had already decided that a was a local scope variable, and made the global one unavailable, thus leading to the traceback.
Is this right? What other explanation is there?