[Tutor] module/package search

spir denis.spir at gmail.com
Mon May 23 19:14:54 CEST 2011


Hello,

I'm developing a package. I need user/test/special modules (inside or outside 
the package) to import given modules from the package, or the whole package or 
a sub-package. I'm looking for a general solution for this.

For an importing module located inside the package, the obvious solution is to 
use a relative import. But this does not work (for what reason?) if the 
importer is not itself imported as element of the package (error: "relative 
import attempted in non package", or such). Even if it's indeed inside the 
package, in a dir with an __init__.py. I've found some posts on this bug, but 
no reason stated, and no solution.
For instance, a test module part of a package cannot import what it is intended 
to test... Same thing for a module that holds its own test suite (and thus 
indeed needs to be run stand- alone).
Note that the package's dir and every subdir hold __init__.py pseudo-modules. 
Is there a solution I'm overlooking to use relative imports?

Now, for using absolute imports, IIUC the package's dir must be on python's 
package search path list, meaning sys.path, is that all? I tried to extend 
sys.path using
* PYTHONPATH
* a custom spir.pth (placed inside /usr/lib/pythonX.Y on Linux)
Both methods fail by me: sys.path still does not hold the package's dir, thus 
absolute imports fail (error: "no module called...").

One more question: in both cases above, I added *both* the package's proper 
dir, and the dir above it, eg both /home/me/prog/python & 
/home/me/prog/python/packname. What's the right one? (the package's top 
__init__.py is in /home/me/prog/python/packname)
In any case, if I manage to add /home/me/prog/python to sys.path, will all 
packages (each located in a sub-dir from there) be found? Or do I need to add 
one path per package, even if they're all grouped in a super-dir?

Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Tutor mailing list