Reason for unintuitive UnboundLocalError behaviour [duplicate]

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?!

Leave a Comment