Unbound Local Error [Solved]

Hello,

I’m encountering a perplexing bug where python does not seem to be recognizing a variable. Another module is importing the following file:

activeI = None
print 'activeI =', activeI

def mouseClick(item):
    if item.iType == "star":
        if activeI != item:
            activeI = item
            item.display()

and it correctly sets the variable activeI. Later mouseClick is called, and the following error occurs:

UnboundLocalError: local variable 'activeI' referenced before assignment

If my knowledge of python is correct, the function should first look to itself for activeI, see nothing, then look up to its parent module and see the variable defined on import. In this case it seems to not be seeing activeI. I use this same structure in another module (a dictionary in that case) and it works fine.

Any ideas?

Thanks very much!
Thaago

The variable needs to be imported from the global scope first, like this:

activeI = None 
print 'activeI =', activeI 

def mouseClick(item):
    global activeI
    if item.iType == "star": 
        if activeI != item

Note that you only need to define it as global if you are modifying the variable’s value (which you are), this is probably why it worked for you in another case.

Ah, of course! Thanks very much for the help.