

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

import sys #

This brings the name “sys” into your module.

(Technically, it binds the name “sys” to the object that is the sys module.)

It does not give you direct 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


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:


So why not do that instead of

import sys


The reason is that the second form will overwrite any 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, or or open?

Can you see how it gets confusing?

Another disadvantage of “from sys import *” is that it makes it harder to find the definition of a name. If you see “sys.exit()” in the code, you know exactly where exit() is defined. If you see “exit()” in a module that has several “from xx import *” statements, you will have to search each imported module for the definition of exit().

The 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 with additions by Kent Johnson]


