469,631 Members | 986 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,631 developers. It's quick & easy.

sys.path and importing modules from other directories

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
Apr 6 '08 #1
0 1352

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Jeff Wagner | last post: by
3 posts views Thread by Stephen Ferg | last post: by
2 posts views Thread by Vsevolod (Simon) Ilyushchenko | last post: by
4 posts views Thread by Jesse B. | last post: by
4 posts views Thread by gnah | last post: by
2 posts views Thread by Dr. Pastor | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.