access to submodules

Peter Otten __peter__ at web.de
Wed Jul 19 11:19:50 EDT 2006


TG wrote:

> if I import tom, it is supposed to load functions defined in
> tom/__init__.py and make all the modules inside accessible through the
> "dot" syntax.
> 
> Therefore, this is supposed to work :
> 
> ?> import tom
> ?> help(tom.core)
> 
> AttributeError: 'module' object has no attribute 'core'
> 
> But if I use the baaaaad star syntax
> 
> ?> from tom import *
> ?> help(core)
> 
> this will work. 

No, it won't. Try again with a fresh interpreter (no prior imports)

>>> from tom import *
>>> core
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'core' is not defined
>>> import tom
>>> tom.core
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'module' object has no attribute 'core'

Only after an explicit import of tom.core...

>>> from tom import core
>>> del core
>>> from tom import *
>>> core
<module 'tom.core' from 'tom/core.py'>

is core added as an attribute to tom and will therefore be copied into the
namespace of a module doing a star-import.

Peter



More information about the Python-list mailing list