Note: there is a very similar question here. However, the bear is with me; my question is not, "Why does the error occur," but "Why was Python implemented to throw an error in this case."
I just stumbled upon this:
a = 5 def x() print a a = 6 x()
throws an UnboundLocalException . Now I know why this happens (later in this area, a bound, so a is considered local throughout the area).
In this case:
a = 5 def x() print b b = 6 x()
it is very important. But the first case has intuitive logic, which should mean this:
a = 5 def x() print globals()["a"] a = 6
I suppose there is a reason the "intuitive" version is not allowed, but what is it? Although this may be the case of “Explicit is better than implicit”, messing around with globals() always feels a little unclean to me.
To put this in perspective, the actual case when this happened to me was someone else's script, I had to change for a 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")
in the script. This insertion takes place inside the function. The module already imported os at the top level (I did not check this) and some os.somefunction calls that were made inside the function, but before my insertion. These calls explicitly UnboundLocalException .
So, can someone explain to me the reasoning for this implementation? Does the user stop making mistakes? Will there be an “intuitive” way to just complicate the work of the bytecode compiler? Or is there a possible ambiguity that I did not think about?