Mutable objects in imported modules
I read that importing a module's mutable objects and changing them in-place,affects the original imported module's objects as well. For instance:
from mymod import x
x[0]=1001
So when I do this:
import mymod
print(mymod.x)
Prints [1001,43,bla]. My question is,does an in-place change this affect a module's compiled byte code,a module's source(unlikely isn't it?) or the namespace that I've imported?So if I change something like that,import at a later time the same module somewhere else and try to a开发者_如何学Goccess the mutable object,what would I get?Cheers.
No, it doesn't. When you import that module at a later time (or if another script imports the module at the same time your program is still running) you get your own, "clean" copy of that module.
So if the test.py
contains the single line x = [1,2,3]
, you get:
>>> 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]
Changes made to a module at run-time are not saved back to disk, but they are active until Python quits:
test.py
stuff = ['dinner is?']
test1.py
from test import stuff
stuff.append('pizza!')
test2.py
from test import stuff
interactive prompt:
--> 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!']
精彩评论