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

Luke Paireepinart rabidpoobear at gmail.com
Fri Jan 8 20:36:11 CET 2010

The difference is a term called "namespace pollution".
the "from socket import *" will place a whole lot of methods into your
global namespace, possibly colliding with other methods / variables you've
defined yourself.  For example, if your file contained

x = 5
from foobar import *

and foobar contained
x = 6

then x would be 6.  This is a potential side-effect that's pretty
undesirable.  If you did the other import style, then x would not get

The reason the 'from' syntax was designed was so you could only import
certain methods into your global namespace, but you'd be aware of which you
were importing.
So in your example you'd want to do
from socket import gethostbyname

so you're sure you know what you're importing into your namespace and you
can avoid polluting it.


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?
> Thanks in advance!
> Rob
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100108/057df1d2/attachment.htm>

More information about the Tutor mailing list