简体   繁体   中英

How to share global variable across the files in python?

I am trying to find a way to share a variable between multiple python scripts. I have the following code:

b.py

my_variable = []

a.py

from b import my_variable  # import the value
def run():
       global x
       x = my_variable.append("and another string")
       print(my_variable)
if __name__ == '__main__':
       run()

c.py

import a
print(a.x)

a.py runs just fine without giving any error. However, when I run the c.py file, it gives off the following error:

Traceback (most recent call last):
File "E:/MOmarFarooq/Programming/Projects/Python Projects/Variables across files/c.py", line 2, in 
<module>
print(a.x)
AttributeError: module 'a' has no attribute 'x'

What I want the code to do is, print the new value of my_variable after it has been changed in a.py . Is there any way I can do that?

the error occurred because you never called the run function from a.py. The if __name__=='__main__': statement is only satisfied if you are running a.py as a program, not importing it as a module. So a.py should be

from b import my_variable  # import the value
def run():
       global x
       x = my_variable.append("and another string")
       print(my_variable)
run()

Note that x will be set to None because the append function does not return anything. It just appends a value to a list.

Well, module 'a' does have no attribute 'x'. Module 'a' has a function that creates a variable 'x', but as long as the method isn't called, the attribute isn't there.

You could change file c.py to:

import a
a.run()
print(a.x)

Another solution would be to make sure that the run() function is always called when importing module 'a'. This is currently not the case, because of the line if __name__ == '__main__': .

If you don't want to run the code but only want to make sure the variable exists, just define it in the module. Before the definition of your run() method, just add x = None (or use any other initial value you prefer).

Note, however, that there other problems with your code and that using globals in this way is a really bad programming pattern, which will likely lead to other problems later on. I wonder what you want to achieve. It probably would be a better solution if you could pass x as argument to the run() function instead of referring to a global variable. But that's outside the scope of this question and difficult to answer without more information.

You need to call the run() function in your c.py file. Here's how the code should be:

import a
a.run()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM