简体   繁体   中英

what makes two python files import a same config file and can influence each other?

maybe this tiltle cannot explain my questions, here has an example.

There are three python files, demo.pyfun.pyconfig.py .

in the config.py file:

from easydict import EasyDict as edict

__C = edict()
cfg = __C
__C.TRAIN = edict()
__C.TRAIN.LEARNING_RATE = 0.001

in the fun.py :

from config import cfg
def function():
    print(cfg.TRAIN.LEARNING_RATE)
    cfg.TRAIN.LEARNING_RATE = 1
    pass

in the demo.py :

from config import cfg
from fun import function

cfg.TRAIN.LEARNING_RATE = 0.1

function()

print(cfg.TRAIN.LEARNING_RATE)

run the demo.py ,results in :

0.1
1

I am curious about why fun.py can change the values in the demo.py although they import a same config file.

Well, you answered your own question: they import the same config file.

Keep in mind you're not changing a value in demo.py or fun.py . Instead, when you do cfg.TRAIN.LEARNING_RATE = 0.1 you're changing the variable in memory cfg , which is tied to config.py .

Since both demo.py and fun.py import the same config.py , the interpreter loads the whole thing into memory once and gives those other two files access to the cfg variable stored in memory. In other words, they're both manipulating the same variable, which they accessed independently.

(The reason the program never outputs 0.001 is that, while cfg.TRAIN.LEARNING_RATE is initialized to that value as soon as you load config.py into memory for the first time, you never actually print it before reassigning it to 0.1 .)

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