Importing * From a Package

Patrick Doyle wpdster at gmail.com
Tue Aug 7 09:16:14 EDT 2007


> 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.
>
ok, that makes sense

> >"[It] imports whatever names are defined in the package [including]
> >any submodules of the package that were explicitly loaded by previous
> >import statements."
This is the part that has me confused -- why does "from package import
*" go on to import names that were explicitly loaded by previous
import statements?

Here is a contrived example (contrived by virtue of culling it out of
an existing code base I was reorganizing into packages when I stumbled
across this:

Directory structure:
./
./SDRGen
./SDRGen/__init__.py
./SDRGen/TFGenerator.py

The SDRGen/__init__.py file is empty.
The SDRGen/TFGenerator.py file contains the following 2 lines:

class TFGenerator:
    pass


Now, at the python prompt I type (and get) the following:

>>> from SDRGen.TFGenerator import *
>>> TFGenerator
<class SDRGen.TFGenerator.TFGenerator at 0xb7eae8bc>
>>> from SDRGen import *
>>> TFGenerator
<module 'SDRGen.TFGenerator' from 'SDRGen/TFGenerator.py'

It looks to me like, when I executed the "from SDRGen import *"
statement, the import "[included a] submodule of the package that
[was] explicitly loaded by [a] previous import statement."  Granted
this example is probably not the best example of style and grace in a
Python program, and I'm in the process of cleaning up things such as
"from ... import *" and naming files and classes with identical names,
but when I stumbled across this I found it confusing, to say the
least.

Why does Python include the submodules that were explicitly loaded by
previous imports?  Does it go out of it's way to do so?  If so, why?
What purpose does it serve?  Or, is it a natural fallout of the manner
in which imports are processed?  If so, could somebody guide my
intuition as to why this would be such a natural fallout?

Thanks for the enlightenment...

--wpd



More information about the Python-list mailing list