Python how to change global variables

I would like to get some kind of confirmation that the download is successful, I have my methods similar to the following. However, the value of the global variable does not change. Please, help

global upload_confirm
upload_confirm = False

def confirm_upload():
    upload_confirm = True

def start_new_upload():
    confirm_upload()
    while (upload_confirm != True):
        print "waiting for upload to be true"
        time.sleep(5)
    if (upload_confirm == True):
        print "start Upload"

start_new_upload()

      

+3


source to share


4 answers


You can try this:

def confirm_upload():
    global upload_confirm
    upload_confirm = True

      



Since you are executing upload_confirm = True

in a local scope, Python treats it as a local variable. Hence, your global variable remains the same.

+3


source


You need to put the statement global

in this scope where you want to access the global variable, that is:



upload_confirm = False

def confirm_upload():
    global upload_confirm
    upload_confirm = True

      

+1


source


Try doing it inside a method confirm_upload()

.

def confirm_upload():
    global upload_confirm #Add this line
    upload_confirm = True

      

You need to declare it global within methods, otherwise it will be local by default.

+1


source


global

the operator must be inside the function.

def confirm_upload():
    global upload_confirm
    upload_confirm = True

      

Otherwise it upload_confirm = ..

will create a local variable.

0


source







All Articles