更新多个文件中的全局字典

时间:2015-09-24 08:35:35

标签: python

我需要更新在多个文件中使用的全局字典并尝试多次 选项,但它没有用。

# test1.py

cell = {'A' : a,
        'B' : b}

# In test2.py

from test1.py import cell
cell['C'] = c  # One way
globals().update(cell)  # did not work also

# In test3.py

from test1.py import cell
print cell  # not getting update cell dictionary

2 个答案:

答案 0 :(得分:2)

如果在当前流程的test3之前没有导入test2,那么当然cell不会被修改...

bruno@bigb:~/Work/playground/impglob$ cat test1.py
cell = { 
    'A' : 1,
    'B' : 2 
    }
bruno@bigb:~/Work/playground/impglob$ cat test2.py
from test1 import cell
cell["C"] = 3
bruno@bigb:~/Work/playground/impglob$ cat test3.py
from test1 import cell
print cell
import test2
print cell
bruno@bigb:~/Work/playground/impglob$ python test3.py
{'A': 1, 'B': 2}
{'A': 1, 'C': 3, 'B': 2}
bruno@bigb:~/Work/playground/impglob$ 

BUT 模块级全局变量(可变全局变量)已经很糟糕,只要有可能就会更好地避免。 共享全局变量 - 一个模块中的代码更新另一个模块中的全局 - 纯粹是邪恶的。 IOW:这样做。有一些方法可以构建你的代码,所以你不需要这么乱。

答案 1 :(得分:1)

python中的模块是singleton。所以他们只进口一次。因此,当您更新任何模块中的可变对象时,它将自动反映在其他模块中。只有在执行test3.py之前在test2.py打印时才会发生这种情况。