[Tutor] Confusion regarding the 'from' statement

Mazhar Hussain yam.matt at gmail.com
Tue Aug 14 20:24:57 CEST 2012


Im new to python and theres something thats bothering me for quite a
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,here 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 does this code work although
considering the problems I mentioned it shouldn't.


More information about the Tutor mailing list