0

I have a problem with python directories.

I have structure like:

  • python
    • modules
      • algorithms
        • cyphers
          • morse.py
    • tests
      • algorithms
        • cyphers
          • test_morse.py

When I try to import module in test I get a module not found error. I am trying to import like:

parent_dir_name = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(parent_dir_name + "/../../../")

from modules.algorithms.cyphers.morse import *

I have also init files in all directories. I am trying to run tests like:

> python -m unittest discover ./tests
martineau
  • 119,623
  • 25
  • 170
  • 301
BousaCZ
  • 31
  • 1
  • 7
  • this appears to be a duplicate of https://stackoverflow.com/questions/456481/cant-get-python-to-import-from-a-different-folder and https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python?rq=1 – alexbhandari Mar 04 '18 at 21:26

2 Answers2

3

It is customary to use relative imports

from ....modules.algorithms.ciphers.morse import *

This ensures that you import the right Morse file, otherwise you risk importing some module named Morse that you've installed.

Here's two examples to illustrate relative imports, say you have a file named simulation.py that has the line

from .animals import Herbivore

In it. This will import the Herbivore class from a file in the same directory as the simulation.py file

Now imagine that you have a folder named tests, in this folder you have a file named test_animals.py, which has the line

from ..animals import Herbivore

This will import the Herbivore class from a file named animals.py located in the folder above the tests folder.

Finally, note that (at least for Python 3.6) can't run a file that uses relative imports, only import it.

Pascal
  • 2,197
  • 3
  • 24
  • 34
Yngve Moe
  • 1,057
  • 7
  • 17
-1

If you mark the directories as modules with __init__.py, you should just be able to import modules via

from modules.algorithms.cyphers import morse
Zenith
  • 245
  • 2
  • 6