【发布时间】:2021-08-17 04:27:37
【问题描述】:
我有一个模块,我在其中读取配置文件并将其存储到变量中。
例如:myconfig.py 看起来像:
cfg = {}
def load(file_path):
global cfg
cfg = cfg_file_todict(file_path)
load() 函数在 main() 函数中调用(即在进程开始时)。
我观察到 cfg 变量不能直接导入,但必须通过模块名称访问。
即,假设我有一个文件 a.py,其中:
import myconfig
print(myconfig.cfg) # This prints the config properly across modules
但如果我有:
from myconfig import cfg
print(cfg) # This prints None
是否有某种方式即使是第二种类型的导入仍然可以保留原始变量?还是有其他替代方案?
【问题讨论】:
-
为什么在函数外使用“全局”关键字?它不是停止导入过程吗?
标签: python-3.x singleton config