Import a module from parent package

Robin Munn rmunn at pobox.com
Sat Mar 20 09:11:46 EST 2004


Peter L. Buschman <plb at iotk.com> wrote:
> I have a package tree laid out like this
>
> foo/bar/module/submodule
> foo/bar/module/submodule/test
> foo/bar/module/submodule/test/test1.py
> foo/bar/module/submodule/test/test2.py
> ...
>
> What I want is for test1.py and test2.py to be able
> to import their parent "submodule" as part of a regression
> testing scheme.  I could do this by putting "import foo.bar.module.submodule"
> in them, but this code won't necessarily always be installed in foo/bar.
>
> Is there a way to do something like this from test1.py and test2.py?
>
> import __parent__.__parent__.submodule
>
> That way, no matter where the entire "module" package gets installed, the
> regression tests will always be able to find and import their parent modules
> whose functionality they need to test.
>
> Essentially, this is like referencing ../../submodule from the command-line.

I needed something very similar last year; I had this directory structure:

topdir/
topdir/usefulmodule.py
topdir/subdir1/
topdir/subdir1/somecode.py
topdir/subdir2/
topdir/subdir2/morecode.py

Both somecode.py and morecode.py needed to use functions from
usefulmodule.py. I solved it as follows:

----- Begin somecode.py -----
import os
import sys
# Other imports...
sys.path.append('..')
import usefulmodule
sys.path.remove('..')
.
.
.
------ End somecode.py ------

----- Begin othercode.py -----
import os
import sys
# Other imports...
sys.path.append('..')
import usefulmodule
sys.path.remove('..')
.
.
.
------ End othercode.py ------

In your case, you'd want to add '../..' to sys.path. I think this will
solve your problem.

-- 
Robin Munn
rmunn at pobox.com



More information about the Python-list mailing list