简体   繁体   中英

Importing a class in another folder

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

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 are 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.

如果使用__init__.py将目录标记为模块,则应该能够通过导入模块

from modules.algorithms.cyphers import morse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM