[Tutor] Confusion regarding the 'from' statement
Joel Goldstick
joel.goldstick at gmail.com
Tue Aug 14 21:02:48 CEST 2012
On Tue, Aug 14, 2012 at 2:43 PM, David Rock <david at graniteweb.com> wrote:
> * Mazhar Hussain <yam.matt at gmail.com> [2012-08-14 23:24]:
>> 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
It is probably better to use:
import mod2
and then use
mod2.test('mod1.py')
instead of your line below
>> 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
>
The reason that import is better than from xxx import has to do with
name collisions. If you have various modules and they all have a test
function, you won't be able to use them all. The last one will be the
only one named test()
> Loosely speaking, it does import the other methods. In order to
> successfully import test(), it has to resolve countLines() and
> countChars(). They won't be directly accessible, as they don't exist
> in the namespace, but test() knows about them. You are reading too much
> into the comment that the module is "deleted".
>
> --
> David Rock
> david at graniteweb.com
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
--
Joel Goldstick
More information about the Tutor
mailing list