antimatter
antimatter

Reputation: 3480

Python import package with and without it's namespace

I have a package called sound with a directory structure like so:

sound/
|-- __init__.py
|-- interpreter.py
|-- blast.py

Before I had the package, interpreter.py would import blast.py with the command import blast. Now with the package I have to say import sound.blast as blast.

While I don't mind this, I'd like to be able to both import the sound package outside of it's directory with that statement, but also to run interpreter.py directly. But if I run interpreter.py directly, I get an import error saying that sound doesn't exist.

My current solution is something like this:

try:
    import sound.blast
except ImportError:
    import blast

But this feels ugly. Is there a better solution for this?

Upvotes: 0

Views: 157

Answers (2)

antimatter
antimatter

Reputation: 3480

The sys.path.append("..") method actually didn't work properly for more complicated namespaces in my program. The best way I solved it was:

if __package__ == 'sound':  
    import sound.blast  
else:  
    import blast

Then more complicated namespaces worked, such as sound.blast.driver.specification

Upvotes: 0

mrcl
mrcl

Reputation: 2180

Another work around would be.

Replace the "try import" statement by the following lines into the interpreter.py file.

import sys
sys.path.append("..")

import sound.blast

Hence the parent directory will also be included in the path, then importing sound.blast within the sound directory wouldn't be a problem any more.

Hope it helps

Upvotes: 1

Related Questions