Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python global variable empty in function

Tags:

python

global

So I've got a couple global variables: directory_name and file_list

They're defined at the top and then I give them values in main. I need their values in a function called checkDirectory(blocknum). If I print their values before I call the function, they're correct, but in the function they are empty. This is some of the code:

file_list = []
directory_name = ""

def checkDirectory(blocknum):
    global directory_name
    global file_list
    directory = tokenize(open(directory_name + '/' + file_list[blocknum], 'r').read())

main():
    try:
        directory_name = sys.argv[1] 
        if not os.path.exists(directory_name):
            print("This is not a working directory.")
            return
    except:
        directory_name = os.getcwd()

    files = os.listdir(directory_name)
    file_list = sorted(files, key=lambda x: int((x.split("."))[1].strip()))
    ....
    checkDirectory(26)

This is a basic 100 line script, and I can pass in the variables but I'll have to do that for three or four functions which will be recursive, so I'd rather not have to do it every time.

like image 395
paulina Avatar asked Dec 01 '25 03:12

paulina


1 Answers

You are shadowing directory_name and file_list in your main function. Since those variables are not known in that scope, they get created locally. In order to operate on the global variables, you need to declare them global in your main() as well:

file_list = []
directory_name = ""

def checkDirectory(blocknum):
    global directory_name
    global file_list
    directory = tokenize(open(directory_name + '/' + file_list[blocknum], 'r').read())

main():
    global directory_name
    global file_list
    ...

Please remember that, as mentioned in the comments, using globals is not good practice and can lead to bad code in the long run (in terms of unreadable/unmaintainable/buggy).

like image 77
Felk Avatar answered Dec 02 '25 16:12

Felk