I’m new to Python and there’s something that’s been bothering me for quite some time. I read in “Learning Python” by Mark Lutz that when we use a from statement to import a name present in a module, it first imports the module, then assigns a new name to it (i.e. the name of the function, class, etc. present in the imported module) and then deletes the module object with the del statement. However what happens if I try to import a name using from that references a name in the imported module that itself is not imported? Consider the following example in which there are two modules mod1.py and mod2.py:
#mod1.py
from mod2 import test
test('mod1.py')
#mod2.py
def countLines(name):
print len(open(name).readlines())
def countChars(name):
print len(open(name).read())
def test(name):
print 'loading...'
countLines(name)
countChars(name)
print '-'*10
Now see what happens when I run or import mod1:
>>>import mod1
loading...
3
44
----------
Here when I imported and ran the test function, it ran successfully although I didn’t even import countChars or countLines, and the from statement had already deleted the mod2 module object.
So I basically need to know why this code works even though considering the problems I mentioned it shouldn’t.
EDIT: Thanx alot to everyone who answered 🙂
I think you’re wrestling with the way python handles
namespaces. when you typefrom module import thingyou are bringingthingfrommoduleinto your current namespace. So, in your example, whenmod1gets imported, the code is evaluated in the following order:And now for mod2:
The reason that all of this is important is because python lets you choose exactly what you want to pull into your namespace. For example, say you have a
module1which defines functioncool_func. Now you are writing another module (module2) and it makes since formodule2to have a functioncool_funcalso. Python allows you to keep those separate. Inmodule3you could do:Or, you could do:
or you could do:
The possibilities go on …
Hopefully my point is clear. When you import an object from a module, you are choosing how you want to reference that object in your current namespace.