Question

I am just starting with python and have troubles understanding the searching path for intra-package module loads. I have a structure like this:

top/                        Top-level package
    __init__.py             Initialize the top package
    src/                    Subpackage for source files
      __init__.py
      pkg1/           Source subpackage 1
         __init__.py          
         mod1_1.py
         mod1_2.py
        ...
      pkg2/           Source subpackage 2
         __init__.py
         mod2_1.py
         mod2_2.py          
         ...
       ...
    test/                  Subpackage for unit testing
      __init__.py
      pkg1Test/      Tests for subpackage1
         __init__.py
         testSuite1_1.py
         testSuite1_2.py
         ...
      pkg2Test/      Tests for subpackage2
        __init__.py
        testSuite2_1.py
        testSuite2_2.py
        ...
    ... 

In testSuite1_1 I need to import module mod1_1.py (and so on). What import statement should I use? Python's official tutorial (at docs.python.org, sec 6.4.2) says:

"If the imported module is not found in the current package (the package of which the current module is a submodule), the import statement looks for a top-level module with the given name."

I took this to mean that I could use (from within testSuite1_1.py):

from src.pkg1 import mod1_1

or

import src.pkg1.mod1_1

neither works. I read several answers to similar questions here, but could not find a solution.

Edit: I changed the module names to follow Python's naming conventions. But I still cannot get this simple example to work.

Was it helpful?

Solution 2

Problem solved with the help of http://legacy.python.org/doc/essays/packages.html (referred to in a similar question). The key point (perhpas obvious to more experienced python developers) is this:

"In order for a Python program to use a package, the package must be findable by the import statement. In other words, the package must be a subdirectory of a directory that is on sys.path. [...] the easiest way to ensure that a package was on sys.path was to either install it in the standard library or to have users extend sys.path by setting their $PYTHONPATH shell environment variable"

Adding the path to "top" to PYTHONPATH solved the problem.To make the solution portable (this is a personal project, but I need to share it across several machines), I guess having a minimal initialization code in top/setup.py should work.

OTHER TIPS

The module name doesn't include the .py extension. Also, in your example, the top-level module is actually named top. And finally, hyphens aren't legal for names in python, I'd suggest replacing them with underscores. Then try:

from top.src.pkg1 import mod1_1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top