I ran into an issue with an inner function I wrote regarding variable scope. I've managed to simply the code down to point to the exact problem. So starting with:
def outer(foo):
def inner(bar):
print(foo)
print(bar)
return inner
if __name__ == "__main__":
function = outer("foo")
function("bar")
I'll get the expected output of :
foo
bar
However, if I try and re-assign foo, I get an error:
def outer(foo):
def inner(bar):
foo = "edited " + foo
print(foo)
print(bar)
return inner
Which gives:
UnboundLocalError: local variable 'foo' referenced before assignment
This reminds me of globals, where you can "read" them normally but to "write" you have to do "global variable; variable=...". Is it the same situation? If so, is there a keyword that allows modification of foo from within inner? Also why? Surely once I've created the function then foo is fixed for that function. I.e. not global. What problem is being avoided here?