2

Suppose I have a project set up as follows:

myproject/ setup.py myproject/ __init__.py module1/ __init__.py a.py b.py test/ __init__.py test.py 

In a.py I have:

from b import Something 

In test.py I have:

from myproject.module1 import a 

When I run test.py I get a ImportError because b cannot be found - since test.py is in a different directory.

I know I can fix this in a.py by writing from myproject.module1.b import Something, but this seems far too verbose to do throughout the project.

Is there a better way?

2
  • Do you need a __init__.py in myproject as well? Is this path in the PYTHONPATH? Commented Jan 11, 2013 at 15:19
  • @Alex Yes, edited (apologies). The myproject that is the parent of module1 is on the PYTHONPATH Commented Jan 11, 2013 at 15:23

3 Answers 3

2

I think you can use

from .b import Something 

Since that's relative, it should always work.

See http://docs.python.org/3/tutorial/modules.html#intra-package-references

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

1 Comment

I'm aware of that, but it seems like a hacky fix. Also, PEP8: "Relative imports for intra-package imports are highly discouraged."
1

from myproject.module1.b import Something is the best way to do it. It may be a little verbose, but it is explicit which is generally a desirable quality in Pythonic code.

1 Comment

While both Freaky Dug and @Evert are correct, this is the better solution based on the PEP8 style guide: "Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports"
1

You can try relative imports in a.py, e.g.

from .b import Something 

But this may not be a complete solution to your problem. As with any modules that import modules/packages in a higher level of the directory structure, you have to be careful how you run it. Specifically, running a module as python submodule.py implicitly sets the module's __name__ variable to "__main__". Since imports (relative and absolute alike) depend on that __name__ and the PYTHONPATH, running a submodule directly may make imports behave differently (or break, as in your case).

Try running your tests.py as

python myproject/module1/test/test.py 

from the top level of the package instead of running it directly.

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.