[Tutor] Importing Modules

Alan Gauld ukc802591034 at btconnect.com
Tue Apr 25 01:28:59 CEST 2006


> I'm having trouble understanding the difference between,
>
> import sys

This brings the *name* "sys" into your module.
It does not give you access to any of the names inside sys itself
(such as exit for example). To access those you need to prefix them with 
sys, as in

sys.exit()

> from sys import *

This does NOT bring the name "sys" into your module, instead
it brings all of the names inside sys(like exit for example) into
your module. Now you can access those names without a prefix, like this:

exit()

So why not do that instead of

import sys?

The reason is that the second form will overwrite and names you
have already declared - like exit say.

exit = 42
from sys import *   # hides my exit variable.

OR more likely, the other way round

from sys import *
exit = 42   # now hides the sys.exit function so I can't use it.

Of course some of these are obvious but there can be a lot
of names in a module, and some modules have the same name
in them, for example:

from os import *
from urllib import *

open(foo)   # which open gets called, os.open or urllib.open?

Can you see how it gets confusing.
Bottom line is it is usually better to accept the extra typing and use

import foo

or for just a few names

from foo import bar,baz

> It seems to me they both do the same thing.

A subtle but very important difference!

HTH,

-- 
Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld





More information about the Tutor mailing list