Question about packages

D

djw

I'm sturcturing my (relatively) large application into packages and am
having trouble understanding one aspect of module/package paths.

If I have a structure like:

in /:
appA.py
__init__.py

in X/:
modX1.py
modX2.py
__init__.py

in Y:/
modY1.py
__init__.py

Now, if I do the following imports and run appA.py, all is well:

in appA.py:
from X import modX1
import Y.modY1

in modX1:
import modX2

in modY1: (as long as run from appA.py)
import X.modX1

But, if I try to create a test harness inside modY1 (in an if statement
checking __name__ with "__main__") and run modY1.py with the last import
(import X.modX1), I get an ImportError.

So, the question is, how do you import into a sub-package to allow both
a script at the root level to import the module ("library mode") and for
the module itself to run in "test harness" mode with the same import?

Any hints appreciated.

-Don
 
M

Mark McEahern

So, the question is, how do you import into a sub-package to allow both
a script at the root level to import the module ("library mode") and for
the module itself to run in "test harness" mode with the same import?

You could do something like:

try:
import X.modX1
except ImportError:
if __name__ == '__main__':
# Hmm, must be running the test harness, adjust
# sys.path appropriately, then retry import
import sys
sys.path.insert(0, whatever)
import X.modX1

but that smells.

Maybe it's best to separate tests from code?

Cheers,

// m
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,173
Messages
2,570,939
Members
47,484
Latest member
JackRichard

Latest Threads

Top