So I was using Python 2.7.15 and I was running into an unexpected error with using global variable inside local scopes function. I know I can get around using "gloabl foo" (I know, not recommended) inside my function, but the error I was expected was not on line number I was expecting.
Code working as expected:
foo = 123
def fooBar():
print foo ### cannot find foo from local scope, checks prev and prints 123
## TEST 2 ##
#foo=987
#print foo
fooBar()
But when I change the code to the following I would expect the same print as Test #1, but instead it blows up on the print statement:
foo = 123
def fooBar():
print foo ### blows up here...
## TEST 2 ##
foo=987
print foo
fooBar()
Traceback (most recent call last):
File "python", line 9, in <module>
File "python", line 4, in fooBar
UnboundLocalError: local variable 'foo' referenced before assignment
I was assuming it would still print '123' and then blow up when I try to assign another value to foo. Almost like Python interpreter parses fooBar() and knows I do an assignment of foo later in local function and then blows up on the print, instead of grabbing global value??
Thanks in Advance! -Kevin