Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for unintuitive UnboundLocalError behaviour

Tags:

python

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?

like image 343
balpha Avatar asked Jul 27 '09 15:07

balpha


1 Answers

Having the same, identical name refer to completely different variables within the same flow of linear code is such a mind-boggling complexity that it staggers the mind. Consider:

def aaaargh(alist):
  for x in alist:
    print a
    a = 23

what is THIS code supposed to do in your desired variant on Python? Have the a in the very same print statement refer to completely different and unrelated variables on the first leg of the loop vs the second one (assuming there IS a second one)? Have it work differently even for a one-item alist than the non-looping code would? Seriously, this way madness lies -- not even thinking of the scary implementation issues, just trying to document and teach this is something that would probably make me switch languages.

And what would be the underpinning motivation for the language, its implementers, its teachers, its learners, its practitioners, to shoulder all of this conceptual burden -- to support and encourage the semi-hidden, non-explicit use of GLOBAL VARIABLES?! That hardly seems a worthwhile goal, does it now?!

like image 95
Alex Martelli Avatar answered Sep 19 '22 06:09

Alex Martelli