简体   繁体   中英

Use and set global variables across multiple files in Python

I have three files. In the first one, I define the global variable.

# file1.py
ABC = 111

In the second file, I change the content of the global variable.

# file2.py
from file1 import *

def set_value():
    global ABC
    ABC = 222

In the third file, I try to use set_value() defined in file2.py to change the contect of the global variable and print it.

# file3.py

from file1 import *
from file2 import *

set_value()
print ABC

The result is 111 not 222. The new value is not set in the global variable. How can I set the global value in file1.py using function in file2.py ?

The line from file1 import * does two things:

  1. It imports the file file1.py into the module cache.
  2. It creates new references of all the defined symbols in your local namespace.

Because you have separate references, you can't update the ones in the module. If those are mutable variables, you can update them and see those updates in the module itself. For example, if you had ABC = [111] you could do ABC[0] = 222 and you would see the change.

If you want to change the module itself, you need to use a reference to the module; modules are mutable!

# file2.py
import file1

def set_value():
    file1.ABC = 222

.

# file3.py

import file1
from file2 import *

set_value()
print file1.ABC

You don't actually want to use the global keyword for this. Similarly to sharing global state with an empty object class, you can create an empty module with which you can assign attributes that will follow it wherever it's been imported. See "How do I share global variables across modules?" from the python3 faq

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