(slightly OT): Python and linux - very cool

Graham Ashton graham at effectif.com
Thu Aug 1 17:59:34 EDT 2002


On Thu, 01 Aug 2002 14:13:04 +0100, Roy Culley wrote:

> In article <3D492CAC.E3A37D82 at engcorp.com>,
> 	Peter Hansen <peter at engcorp.com> writes:
>> 
>> "from x import *" certainly works
>> properly, even though it's almost never a good idea (hint to newbies:
>> don't do that!).
> 
> I'm a python newbie. How's about expanding on the hint. I just do (as an
> example):
> 
> import os, re, sys, string

Nope, that's absolutely fine. You are only adding the four modules that
you are importing to your current name space.

When you do "from somemodule import *" you will be importing absolutely
everything that the module or package exposes to you. This means that you
can very easily get difficult to find clashes between the names in
somemodule and the names that exist in your current namespace.
Consequently it's generally not a good idea.

For example, if you do "from os import *" you'll find that the builtin
open() function seems to start behaving strangely (because it's been
hidden by os.open(), which is a different function with a different
interface).

I say "generally not a good idea" above because some modules are actually
designed to be used this way (e.g. gtk).

There is also another more subtle side effect of "import *". If you find
yourself importing multiple modules into a file it can quickly become
difficult to keep track of which functions or classes are defined in which
module.

This makes locating the docs or code for a function an order of magnitude
more difficult, especially for other people. In other words, you're
impacting your maintainability. What I'm getting at here is that saying
somemodule.do_foo() is more "self documenting" than saying do_foo().

--
Graham



More information about the Python-list mailing list