导入模块中的可变对象
我看到有人说,如果你导入一个模块里的可变对象(也就是可以改变的对象),然后直接修改它,这样会影响到原来导入的模块里的对象。
from mymod import x
x[0]=1001
比如说,当我这样做的时候:
import mymod
print(mymod.x)
输出是 [1001, 43, bla]。我的问题是,直接修改这些对象会不会影响到模块的编译字节码、模块的源代码(这不太可能吧?)或者我导入的命名空间?如果我在其他地方再导入同一个模块,然后尝试访问这个可变对象,我会得到什么呢?谢谢。
2 个回答
1
在程序运行时对一个模块所做的修改不会被保存到硬盘上,但这些修改在Python程序运行期间是有效的,直到你退出Python:
test.py
stuff = ['dinner is?']
test1.py
from test import stuff
stuff.append('pizza!')
test2.py
from test import stuff
交互式提示:
--> import test
--> test.stuff
['dinner is?']
--> import test1
--> test.stuff
['dinner is?', 'pizza!']
--> import test2
--> test2.stuff
['dinner is?', 'pizza!']
--> test.stuff
['dinner is?', 'pizza!']
3
不,它不会。当你在稍后的时间导入那个模块时(或者如果另一个脚本在你的程序还在运行的时候导入这个模块),你会得到你自己的一份“干净”的模块副本。
所以如果 test.py
里面只有一行 x = [1,2,3]
,你会得到:
>>> from test import x
>>> x[0] = 1001
>>> x
[1001, 2, 3]
>>> import test
>>> test.x
[1001, 2, 3]
>>> imp.reload(test)
<module 'test' from 'test.py'>
>>> test.x # test is rebound to a new object
[1, 2, 3]
>>> x # the old local variable isn't affected, of course
[1001, 2, 3]