Mechanism Python import package is import incoming and module systems are placed in sys.module
the dictionary inside
Py import multiple files at a time, will go to sys.module
whether there has been import inspection, and if you have import, the import will not repeat, otherwise import came
from aaa.yyy import x
Is not the same, test.py in this way from import
, then x is test their own namespace of variables. So x is only valid in test.py in any case for x changes can not affect the x yyy
That is
from yyy import x
equivalent to
improt yyy
x= yyy.x # 当你执行x=2时,完全影响不到yyy.x
So, if you need shared variables, do not use this form yyy import x from, but the use of import file, then can be used by yyy.x, then yyy.x = 'abc' can be modified. Such treatment of global variables can be shared. That is, to maintain a separate namespace, this does not import python again to achieve sharing.
Example:
# 目录树
multi_module
│ main.py
│ val_sync.py
# val_sync.py
DICT = {
'a':1,
'b':2,
}
# main.py
import val_sync as mv
print(mv.DICT)
mv.DICT['c'] = 3
print(mv.DICT)
mv.DICT.pop('a')
print(mv.DICT)
python main.py
out:
{'a': 1, 'b': 2}
{'a': 1, 'b': 2, 'c': 3}
{'b': 2, 'c': 3}