[Tutor] Tutor FAQ
Kent Johnson
kent37 at tds.net
Thu May 4 03:55:00 CEST 2006
Mike Hansen wrote:
> ---------------------------------------------------------------------
> 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 access to any of the names inside sys itself (such
> as
does not give you _direct_ access...
> 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.
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().
> Bottom line is it is usually better to accept the extra typing and use
The bottom line...
>
> import foo
>
> or for just a few names
>
> from foo import bar,baz
>
> [from a post on Python Tutor by Alan Gauld]
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
More information about the Tutor
mailing list