Importing * From a Package

Jean-Paul Calderone exarkun at divmod.com
Mon Aug 6 10:32:53 EDT 2007


On Mon, 6 Aug 2007 10:06:51 -0400, Patrick Doyle <wpdster at gmail.com> wrote:
>Reading through the Python tutorial, I got to section 6.4.1,
>"Importing * From a Package", which states:
>
>"If __all__ is not defined, the statement from Sound.Effects import *
>does not import all submodules from the package Sound.Effects into the
>current namespace; ..."
>
>It then goes on to state:
>
>"[It] imports whatever names are defined in the package [including]
>any submodules of the package that were explicitly loaded by previous
>import statements."
>
>I am curious to learn the rationale for this behavior, since it just
>caught me by surprise (hence the reason I was pouring over the
>tutorial document in such detail :-))

There's no reliable way to differentiate between names which you defined
using something other than an import statement, names you defined with an
import statement with the intent of publishing them as part of your external
API, and names you defined with an import statement which you only intended
to use internally.  So Python doesn't even try to differentiate betweem them.

>
>Thus far, everything in Python has seemed very intuitive to me,
>however the behavior of "from package import *" baffles me.
>
>So I figured I'd ask -- why does Python behave this way.
>
>(And now, I'm going to do some code cleanup :-))
>

You should probably remove all uses of "import *" from your code.  It's
only a very mild convenience at the time of initial use, and forever
after that it is a maintenance burden, causing anyone who wants to read
the code at any future point to have to dig through various layers of
definitions before they can find out what any particular name is bound
to, and potentially leading to bugs where names from one package accidentally
obscure names from another package.

Jean-Paul



More information about the Python-list mailing list