0

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?

4
  • Why do you want to be able to run interpreter.py directly? Commented Mar 5, 2014 at 12:30
  • For flexibility I guess. It's not a big deal since I prefer the package and namespace, but I can imagine a scenario where someone tries to use my package and can't figure out how to use it because they try to run interpreter.py directly. Commented Mar 5, 2014 at 12:39
  • I don't think that use case is important enough that you should want to do this. Commented Mar 5, 2014 at 12:40
  • I also have a command line arguments for the interpreter. I don't want to always be importing the package. I want users to be able to run it with command line args. Commented Mar 5, 2014 at 14:35

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.