There’re two scripts:
#imptee.py
foo = "abc"
def show():
print "foo from imptee:",foo
#impter.py:
#!/usr/bin/env python
from imptee import *
show()
foo = 123
print "foo from impter:",foo
show()
When I run impter.py, it yields the following result:
foo from imptee: abc
foo from impter: 123
foo from imptee: abc
I just don’t understand why after assigning 123 to variable foo, show() still print ‘abc’, not 123. I think after "from imptee import *", foo and show() are in global namespace now, and there are no local namespace. I do understand that the searching sequence should be: local namespace, global namespace, bulit-ins namespece. So, why is that? Could someone give me a hand, please?
THX!
Modules have separate namespaces. When you import from one module to another, you are importing the values (usually functions but in this case a literal “abc”) from the source module and assigning them to names in the destination module.
When you do
from imptee import *, you are assigning them to the same name that they had in the source module, but that doesn’t actually change the pointers in the source module. It just duplicates the names.When you change the assignment in the destination module after the import, that doesn’t change anything in the source module, because even though the names look the same they are separate pointers and can point to separate things.
This might be more clear if you did
import impteeand then manually assigned the value:foo = imptee.foo. Then later you’ll dofoo = 123, and it makes sense that the value of foo in the destination module has changed but the value of the similarly-named pointer in the source module has not.