Package hierarchies and cross-directory 'import'

Ben Finney bignose-hates-spam at and-zip-does-too.com.au
Sat Apr 12 00:42:51 EDT 2003


On Tue, 08 Apr 2003 00:07:56 GMT, Ben Finney wrote:
>  On Mon, 7 Apr 2003 10:45:58 GMT, Michael Hudson wrote:
> > It is a Fact Of Life that Python packages (and modules therein)
> > need to know where they are in the global module namespace.
>  
> I feel dim for not being able to see the answer, but it seems absurd
> to me that one can't rename a directory and expect the scripts within
> it to continue working without outside help.

Responses have ranged from "Yes, it is a really annoying flaw, I wish it
would be fixed" to "Obviously if you can't do it in Python it shouldn't
be done".

The former, while sympathetic, doesn't help.  The latter is rather
head-in-the-sand.  In the meantime, I need a solution.  So I've hacked
one up.

In each package directory, I'll place a version of this _path.py file.
The module_depth constant is set to the number of directories below the
"root" of the package tree.  Then, each module in the directory needs
only to 'import _path' to ensure the root module directory is in the
module search path.

It's a nasty hack.  I find it to be the best option at present, because:

It could be written more concisely, but I prefer readability.

It's somewhat more maintainable than hard coding 'sys.path.append(
"../.." )' into every two-level deep module (and changing it whenever
that module needs to move to a different level).

It can be copied as-is to any package directory within the tree, and
modifying the module_depth constant.

It's far preferable to having the actual filesystem path hard-coded
somewhere (and having the whole package tree fail when the directory is
renamed or moved to someone else's system).

But, gosh, why on earth is this even necessary?  Importing with relative
paths would be so much simpler, no?


_path.py:
=====
#!/usr/bin/python
# _path.py

""" Path initialisation for modules in this package
"""

import sys
import os.path

# Specify how deep this package is in the tree
module_depth = 2

# Get the directory of this module
this_dir = os.path.dirname( __file__ )

# Get the directory of the root module
root_module_dir = this_dir
for i in range( 0, module_depth ):
    root_module_dir = os.path.join( root_module_dir, '..' )

root_module_dir = os.path.normpath( root_module_dir )

# Append the root module directory to the module search path
if( not root_module_dir in sys.path ):
    sys.path.append( root_module_dir )

#
# End of _path.py
=====

-- 
 \     "A cynic is a man who, when he smells flowers, looks around for |
  `\                                   a coffin."  -- Henry L. Mencken |
_o__)                                                                  |
http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B




More information about the Python-list mailing list