[Tutor] Question on "import foobar" vs "from foobar import *"

Wayne Werner waynejwerner at gmail.com
Fri Jan 8 20:51:49 CET 2010

On Fri, Jan 8, 2010 at 1:21 PM, Rob Cherry <pythontutor at lxrb.com> wrote:

> Still trying to get the hang of some python intricacies, but this one
> has come up a few times.  Beyond the obvious syntactic niceties what
> is the difference between importing with and without the "from"
> syntax?
> Its nice for example to do this -
> from socket import *
> googleip = gethostbyname("www.google.com")
> vs
> import socket
> googleip = socket.gethostbyname("www.google.com")
> Is there any difference between these concepts?  Is there an easy
> google search term for me to research the difference to death?

Namespace is a term you might want to look for. (Google "Python Namespace"
or something to that effect)

What the first one does is import all of the variables, classes, functions,
and anything inside the socket library into the local namespace.

This can lead to some pretty unpredictable behavior and is usually
discouraged. It's better to import socket (or whatever module you want to
import). But if you know you just want one function or class, you can use
the "from" syntax to import it.


To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100108/49c5d3cf/attachment.htm>

More information about the Tutor mailing list