1

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?

4
  • How are you running this? Commented Jul 22, 2018 at 3:47
  • Where are your __init__ files? Commented Jul 22, 2018 at 3:49
  • python3 tests/tests.py Commented Jul 22, 2018 at 3:50
  • I do not create any init file. Is it necessary? Commented Jul 22, 2018 at 3:51

1 Answer 1

3

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.)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Run python -m tests.tests fix my test. But now other importations in my code broken. When I use import any_name in other file in my_project I need to put .any_name and when I run my program 'ImportError: attempted relative import with no known parent package'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.