Importing and packages

skaller skaller at maxtal.com.au
Fri Oct 29 01:51:43 EDT 1999


I have some confusion discovering what Python actually does,
and what it is supposed to do, importing modules.
So I am presenting an algorithm I intend to implement for Viper,
in the hope someone more knowledgeable than me of what Python
does, should do, and will do in 1.6/2.0, will comment.

Here is the situation. When an import has a module name
of the form

	top.sub1.sub2 ... subn

then the 'sub' components will always be loaded
from the directory containing the 'parent'
component, if there is no file, an ImportError is raised.

Now the hard bit, loading 'top'. First, top is
searched for in the directory of the module
containing the import statement. If it is found there,
it is loaded as as

	parent.top

where 'parent' is the name of the importing module,
with one exception: if the importing module is
the main file __main__, the module is just named

	top

but it is considered a submodule of the __main__ package.
in this sense __main__ is considered as the __init__
module of a package, and the directory containing
the main file is considered as a package directory.
This means relative loading is conditionally supported
with respect to the main file (and recursively).

If top is NOT found in the directory of the importing
module, then sys.path is searched, and the module
(if found) is a top level module named

	top

The mechanism I used DOES NOT POLLUTE sys.path,
as Python 1.5.2 does.

[To implement this, Viper modules contain an attribute

	__directory__

which names the directory containing the file
(which is named in __file__: the directory variable
simply eases the burden of parsing the tail off)]

-- 
John Skaller, mailto:skaller at maxtal.com.au
1/10 Toxteth Rd Glebe NSW 2037 Australia
homepage: http://www.maxtal.com.au/~skaller
downloads: http://www.triode.net.au/~skaller




More information about the Python-list mailing list