[Tutor] Tutor FAQ

Mike Hansen mahansen at adelphia.net
Thu May 4 03:18:57 CEST 2006


---------------------------------------------------------------------
What's the difference between "import foo" and "from foo import *"?

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

[from a post on Python Tutor by Alan Gauld]



More information about the Tutor mailing list