Newbie Question

Jeff Shannon jeff at ccvcorp.com
Wed Oct 10 19:07:27 EDT 2001


Janos Blazi wrote:

> (3)
> >>>from string import *
> then you can use +every+ function from string without the "string."-prefix
>

A word of warning about this idiom, though--it has several serious drawbacks.

First, it makes your code harder to understand, because it's not apparent
where you're getting your functions from.  When someone is reading through
your code, they have no way of knowing if a given function is a builtin,
defined elsewhere in that module, or from the string module (or whatever other
modules you may have imported this way).

Second, if you are working interactively, it becomes difficult to use any
changes you make to a module.  In order to have changes take effect, you need
to 'reload(module)', but if you've done 'from module import ...', then there's
no module name to reload.

Finally, and most importantly, this is a good way to "lose" functions.
Suppose you have a module "utils" which has a function "list()", that returns
a list of whatever you're working with.  You can import this module the normal
way, 'import utils', and then call your function 'mylist = utils.list()', and
all is well.  But if you import it by 'from utils import *', then you refer to
the function like 'mylist = list()'.  However, there's a built-in function
list(), which is normally called in that same way.  Now you've hidden that
built-in function, and can no longer call it.  (Technically, it is possible to
call it as __builtin__.list(), but this is ugly and not good practice to rely
on...)

In short, it really is best, in 99% of all circumstances, to use 'import
module', 'module.function()' syntax.  There are a few modules that are
specifically designed to be used as 'from x import *' (e.g., Tkinter and
wxPython), but they are definately the exception, and it's not a good idea to
get in the habit of using that syntax regularly.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list