bcoughlan
bcoughlan

Reputation: 26627

Importing a module which imports from same directory

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?

Upvotes: 2

Views: 122

Answers (3)

Ryan Artecona
Ryan Artecona

Reputation: 6203

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.

Upvotes: 1

Freaky Dug
Freaky Dug

Reputation: 1035

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.

Upvotes: 1

user707650
user707650

Reputation:

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

Upvotes: 2

Related Questions