Note: There is a very similar question here. Bear with me, however; my question is not "Why does the error happen," but "Why was Python implemented as to throw an error in this case."
I just stumbled over this:
a = 5
def x()
print a
a = 6
x()
throws an UnboundLocalException
. Now, I do know why that happens (later in this scope, a
is bound, so a
is considered local throughout the scope).
In this case:
a = 5
def x()
print b
b = 6
x()
this makes very much sense. But the first case has an intuitive logic to it, which is to mean this:
a = 5
def x()
print globals()["a"]
a = 6 # local assignment
x()
I guess there's a reason why the "intutive" version is not allowed, but what is it? Although this might be a case of "Explicit is better than implicit," fiddling around with the globals()
always feels a bit unclean to me.
To put this into perspective, the actual case where this happened to me was someone else's script I had to change for one moment. In my (short-lived) change, I did some file renaming while the script was running, so I inserted
import os
os.rename("foo", "bar")
into the script. This inserting happend inside a function. The module already imported os
at the top level (I didn't check that), and some os.somefunction
calls where made inside the function, but before my insert. These calls obviously triggered an UnboundLocalException
.
So, can someone explain the reasoning behind this implementation to me? Is it to prevent the user from making mistakes? Would the "intuitive" way just make things more complicated for the bytecode compiler? Or is there a possible ambiguity that I didn't think of?