Importing * From a Package

Patrick Doyle wpdster at gmail.com
Tue Aug 7 10:38:32 EDT 2007


On 7 Aug 2007 13:54:21 GMT, Duncan Booth <duncan.booth at invalid.invalid> wrote:
> "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 '_').
>
Ahhh, I see it now
>>> import SDRGen
>>> dir()
['SDRGen', '__builtins__', '__doc__', '__name__']

>>> dir(SDRGen)
['__builtins__', '__doc__', '__file__', '__name__', '__path__']

>>> from SDRGen import *
>>> dir()
['SDRGen', '__builtins__', '__doc__', '__name__']
>>> dir(SDRGen)
['__builtins__', '__doc__', '__file__', '__name__', '__path__']
(notice, no changes)

>>> from SDRGen.TFGenerator import TFGenerator
>>> dir()
['SDRGen', 'TFGenerator', '__builtins__', '__doc__', '__name__']
>>> TFGenerator
<class SDRGen.TFGenerator.TFGenerator at 0xb7ee80ec>
(as expected)

>>> dir(SDRGen)
['TFGenerator', '__builtins__', '__doc__', '__file__', '__name__', '__path__']
>>> SDRGen.TFGenerator
<module 'SDRGen.TFGenerator' from 'SDRGen/TFGenerator.pyc'>

and that's what led to my confusion... when my script later did a
>>> from SDRGen import *

The 'TFGenerator' name got changed from a reference to the
'TFGenerator' class to a reference to the 'SDRGen.TFGenerator' module.

and now it makes sense.

Thanks.

--wpd



More information about the Python-list mailing list