Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python global variable scoping

Im trying to declare some global variables in some functions and importing the file with those functions into another. However, I am finding that running the function in the second file will not create the global variable. I tried creating another variable with the same name, but when i print out the variable, it prints out the value of the second file, not the global value

globals.py

def default():
    global value
    value = 1

main.py

from globals import *
value = 0
def main():
    default()
    print value

if __name__=='__main__':
    main()

this will print 0. if i dont have value = 0 in main, the program will error (value not defined).

If i declare value in globals.py outside of the function, main.py will take on the value of the global value, rather than the value set in default()

What is the proper way to get value to be a global variable in python?

like image 725
calccrypto Avatar asked Mar 24 '13 05:03

calccrypto


1 Answers

Globals in Python are only global to their module. There are no names that you can modify that are global to the entire process.

You can accomplish what you want with this:

globals.py:

value = 0
def default():
    global value
    value = 1

main.py:

import globals
def main():
    globals.default()
    print globals.value

if __name__ == "__main__":
    main()

I have no idea whether a global like this is the best way to solve your problem, though.

like image 149
Ned Batchelder Avatar answered Sep 22 '22 09:09

Ned Batchelder