CAB
CAB

Reputation: 155

error in import in Python 3

I have the structure in Python 3:

my_module/
    my_module/
        any_name.py
    tests/
        tests.py

Then, I am trying to use in tests.py:

from my_module.any_name import my_class

And I am receiving the error:

ModuleNotFoundError: No module named 'my_module'

Does anyone know what is the problem?

Upvotes: 1

Views: 90

Answers (1)

abarnert
abarnert

Reputation: 365717

First, it's pretty confusing to have my_module and my_module/my_module, but let's ignore that.

In order for my_module to work, the outer my_module has to be on your sys.path.

So, if you do this:

$ cd tests
$ python tests.py

… then your sys.path will just by your usual path, plus my_module/tests. It won't include my_module, so you can't find my_module/my_module anywhere.

Ways around this include:

  • Have a top-level test.py that does from tests import tests.py and tests.run().
  • Run you code as python -m tests.tests from the top-level my_module directory, instead of running it as python tests.py from my_module/tests.
  • Have tests/tests.py insert os.path.join(__path__, '../my_module) into sys.path manually.
  • Use setuptools/pkg_resources instead of trying to do everything manually.
  • Do the hacky old-style thing described here. (You really don't want to do this unless you need to be compatible with Python 2.7 or 3.2 or old distribute/distutils versions of pkg_resources.)

Upvotes: 3

Related Questions