sys.path and importing modules from other directories

Martin P. Hellwig xng at xs4all.nl
Sat Apr 5 22:04:12 EDT 2008


Hello all,

I had some troubles in the past how to arrange my packages and modules, 
because I usually don't develop my stuff in the Lib\site-packages 
directory I have some troubles when importing depending modules that are 
in 'sibling' directories. Like in the following scenario:
pkg_root\
-__init__
- common\
- - __init__
- - something
- other\
- - __init__
- - working_on

So when I am busy with 'working_on' and want to import from common 
something it won't let me do that because I don't have pkg_root in my 
path. No biggy here, I just add the pkg_root to the path. Once I am 
finished most of the time all modules are initiated from a module 
directly at the pkg_root level so then importing works without worries.

However it has irritated me enough that I wrote a little script I called 
'relative_path.py' that I put in my python path that does these things 
for me, so that I only need to import that one and set the parent path, 
probably I missed a point here somewhere but if not maybe somebody else 
finds it useful.

So while I am developing the depending modules, these modules begin with:
import relative_path
relative_path.add_package_root()


+++
import os, sys

def getparent(depth=0):
     "Returns the absolute pathname of (grand)parents directory."
     # By default it returns the current working directory.
     # The level of 'grand' is set by depth.

     getcwd = os.getcwd
     sep = os.sep
     abspath = os.path.abspath
     if depth == 0:
         grand = None
     else:
         grand = depth * -1

     # Main function
     # From the current working directory get the absolute path,
     # split it and join the wanted portion of the list.
     pathname = sep.join(abspath(getcwd()).split(sep)[:grand])

     # Make sure to throw an exception if depth results in an empty string.
     if len(pathname) == 0:
         raise_string = "(grand)Parent depth of %s is before root." % depth
         raise(LookupError(raise_string))
     else:
         return(pathname)


def add_package_root(directory=1):
     "Add a parent directory relative to cwd to sys.path, default the 
first."
     sys.path.append(getparent(directory))
+++

-- 
mph



More information about the Python-list mailing list