I have a little problem with local variables and python (2.7).
I have a little code :
def foo(a):
def bar():
print a
return bar()
>>>foo(5)
5
Well, it’s working, but if want to modify a , like this :
def foo(a):
def bar():
a -= 1
return bar()
>>>foo(5)
UnboundLocalError: local variable 'a' referenced before assignment
So I must affect ‘a’ to another variable.
But I don’t understand this comportment.
Is it because when there is an assignment, python looks in the locals() variables and doesn’t find it ?
Thanks.
You’ve found something that used to be an issue in Python! The short answer is that you can’t do this in Python 2.x (though you can simulate) it, but you can in 3.x using the
nonlocalkeyword.See PEP 3104: