[Tutor] Difference between >>> import modulex and >>> from modulex

exnihilo at myrealbox.com exnihilo at myrealbox.com
Sat Jan 3 07:15:43 EST 2004


hi Todd,

Todd G. Gardner wrote:

>Hello Everyone,
>
>I have some questions that I must have skipped the answers in the tutorial.
>Pardon me if they are obvious.
>
>1) What is the difference between ">>> import modulex" and ">>> from modulex
>import *"?
>
>  
>
Others will certainly give you more definitive answers, but as I 
understand it, the difference is in whether the contents of the module 
get imported or the module as a whole gets imported into the current 
namespace. This is clearer when you consider how you refer to what was 
imported in the two cases.

If there were a function foo in modulex, then after doing "import 
modulex", I call the function by doing something like "modulex.foo()". 
The import added an entry for modulex to the symbol table for the 
current module, so to access something in modulex, i do 
"modulex.something".

If, on the other hand, I had done "from modulex import foo", then that 
would have added foo to the current namespace (and not added an entry 
for the module as in the previous example). The foo function would be 
part of the current namespace, and i could call it with just "foo()" 
(modulex.foo() would not work). The same goes for any kind of attribute 
within the module i'm importing, whether they're functions, classes, 
constants, or whatever.

Here is a little illustration (with some # comments):
 >>> import urllib2 # this doesn't import the contents of urllib2 into 
the current namespace, it just adds an entry for the module to the 
symbol table of this module
 >>> f = urllib2.urlopen('http://www.google.com')  # so i have to refer 
to the urlopen function of the module as urllib2.urlopen
 >>> googlehtml = f.read()
 >>> f.close()
 >>> # print googlehtml would show all the html code i just downloaded 
from google
If i used "from module import attribute", then it would be as follows:
 >>> from urllib2 import urlopen
 >>> f = urlopen('http://google.com') # i can now use urlopen unprefixed 
by its module name
 >>> googlehtml = f.read()
 >>> f.close()

>2) What happens when the command reads ">>> from modulex import something"?
>    2a) Is something a function that is imported from modulex?
>
>  
>
I'm not sure exactly what you're refering to in 2), but "from modulex 
import something" would import into the current namespace whatever 
something refers to (this will often be a class), and you would be able 
to refer to it with just 'something' (without the quotes), instead of 
modulex.something

I hope this helps. If not, don't worry, clearer explanations will follow...

-n.




More information about the Tutor mailing list