Little
Little

Reputation: 3477

global variable in Python, is this normal behaviour?

I have been using WinPython for coding a program that uses a global variable, this is the code:

def main():
    global listC
    listC=[1,2,3,4,5]

def doSomething():
    if listC!=[]:
        pass

The problem that I have is that the line that says if listC!=... throws me a warning that says "undefined name listC"; this program actually compiles and executes normally, but I would like to know why that warning appears if I have declared list as a global variable.

I would like to execute it in the following way:

programName.main()       //init the list
programName.doSomething()    //do an operation with the list
programName.doSomething()     //same as before
...

Thanks

Upvotes: 0

Views: 72

Answers (2)

whitebeard
whitebeard

Reputation: 1131

This should be working... It works for me.

def doSomething():
   if listC != []:
       print "success!"

def main():
    global listC
    listC = [1,2,3,4,5]
    doSomething()

>>> main()
success!

Upvotes: 0

jsbueno
jsbueno

Reputation: 110186

With the parts of the code you are showing us, it should work - however, since you are getting the error, what is going on is that you are making an assignment to listC at some point in the body of the doSomething function.

If there is any such assignment, Python will regard the listCvariable as local to doSomething - unless you put list it as global at the beggining of the function - and, of course, you also have to declare it as global in the function you initialize it - main in this case, and be sure that the initalization code runs prior to calling doSomething.

def main():
    global listC
    listC=[1,2,3,4,5]

def doSomething():
    global listC
    if listC != []:
        print "success!"
    # the following statement would trigger a NameError above, if not for the "global":
    listC = [2,3]

Upvotes: 1

Related Questions