Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...