Python global variable scoping

2019-01-09 15:49发布

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?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-09 16:19

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.

查看更多
登录 后发表回答