简体   繁体   English

是什么使两个python文件导入同一个配置文件并且可以相互影响?

[英]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 . 一共有三个python文件, demo.pyfun.pyconfig.py

in the config.py file: config.py文件中:

from easydict import EasyDict as edict

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

in the fun.py : fun.py

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

in the demo.py : 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 : 运行demo.py ,结果是:

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. 我很好奇,为什么fun.py可以更改值demo.py虽然它们导入相同的配置文件。

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 . 请记住,您没有更改demo.pyfun.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 . 相反,当您执行cfg.TRAIN.LEARNING_RATE = 0.1您正在更改内存cfg的变量,该变量绑定到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. 由于demo.pyfun.py导入相同的config.py ,因此解释器将整个事件一次加载到内存中,并赋予其他两个文件访问存储在内存中的cfg变量的权限。 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 .) (程序从不输出0.001的原因是,当cfg.TRAIN.LEARNING_RATEconfig.py加载到内存时cfg.TRAIN.LEARNING_RATE被初始化为该值,而在将其重新分配为0.1之前,您从未真正打印过它。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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