3

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?

Albion
  • 135
  • 5
  • 1
    See https://www.python-course.eu/python3_global_vs_local_variables.php – jarmod May 12 '20 at 23:22
  • 1
    The rule in Python is that an assignment to a variable *anywhere in scope* will make the variable act as local *everywhere* in that scope. In CPython, variables are marked as local at compile time. Anway, see [this answer from the official FAQ](https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value) – juanpa.arrivillaga May 12 '20 at 23:34
  • Thank you folks, both resources explain it beautifully! – Albion May 14 '20 at 05:11

0 Answers0