module confusion

Steve Holden steve at holdenweb.com
Tue Oct 2 18:31:20 EDT 2007


Lawrence D'Oliveiro wrote:
> In message <mailman.1379.1191301581.2658.python-list at python.org>, Robert
> Kern wrote:
> 
>> Not all of the modules in a package are imported by importing the
>> top-level package.
> 
> You can't import packages, only modules.
> 
>> os.path is a particularly weird case because it is just an alias to the
>> platform-specific path-handling module; os is not a package.
> 
> os is a module, os.path is a variable within that module. That's all there
> is to it.

The Python  documentation could probably be a little more expansive on 
the import front, but it's an area where historically many different 
attempts have been made to fix up the problems, or create new and more 
usable layers [that suffer from different problems].

You *can* import a package, and a package is just a *little* different 
from a module in that the __init__.py file in the package directory 
provides the source for the first-import execution instead of the 
modulename.py file. The global namespace during this process is the 
package's global namespace, so if further imports are executed by the 
__init__ module the names of the imported objects are created in the 
package global namespace (along with the names of defined classes and 
functions, and other names bound by assignment) and can therefore be 
referenced relative to it. The package in which the package import was 
executed  will end up defined in the namespace in which the import 
statement was executed.

I will grant that you can't basically do anything in the __init__.py 
that you can't do in a module's modulename.py file. It is possible to 
define a hierarchy of namespaces concordant with the package's directory 
structure, but it doesn't matter whether package import creates the 
hierarchical namespace or assignment does. You can access module 
namespaces in a hierarchical way.

That's about all that can be said without delving into the murky land of 
relative vs. absolute imports. That can be for another day. And another 
writer, probably.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline




More information about the Python-list mailing list