Importing * From a Package

Duncan Booth duncan.booth at invalid.invalid
Tue Aug 7 09:54:21 EDT 2007


"Patrick Doyle" <wpdster at gmail.com> wrote:

> 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?
> 

It is a natural fallout of the manner in which imports are processed. 
When you explicitly load a submodule a reference to the submodule is 
stored in the parent module. When you do 'from module import *' and the 
imported module doesn't define __all__, you create a reference in the 
current module to everything referenced by the imported module (except 
for variables beginning with '_').

Python makes no distinction at all between the objects named in the 
imported module: they all get imported, i.e. assigned into the current 
scope no matter how they got there.

If you use your example:

>>> import SDRGen
>>> dir(SDRGen)
['__builtins__', '__doc__', '__file__', '__name__', '__path__']
>>> from SDRGen.TFGenerator import *
>>> dir(SDRGen)
['TFGenerator', '__builtins__', '__doc__', '__file__', '__name__', 
'__path__']
>>>

The line 'from SDRGen.TFGenerator import *' always creates the name 
TFGenerator in the SDRGen module (and it will create the SDRGen module 
if it has to). A subsequent 'from SDRGen import *' is simply doing the 
equivalent of:

    for name in dir(SDRGen):
       if not name.startswith('_'):
           setattr(current_module, getattr(SDRGen, name))

except of course the variables name and current_module don't exist.



More information about the Python-list mailing list