Search code examples
pythonpython-module

import not working in python with multiple directory


Project_folder
    main.py
    folder_x
        __init__.py
        A.py
        B.py
    folder_y
        __init__.py
        C.py
        D.py

I have a project structure like the above. In main.py, I am importing A.py

from folder_x.A import A

And in A.py file I have

from B import B

But it's giving

    from B import B
ModuleNotFoundError: No module named 'B'

I have found some answers (Updating sys path) to some related questions. But is there any other way? And I am not also allowed to modify A.py or B.py


Solution

  • Python Interpreter does not interpret your code in the way you are trying to assume.

    whenever you check - print(sys.path) all the paths which are listed are available to use import statement for python, and it must be used to import in proper hierarchy in order for you to perform operation successfully.

    Since you are executing project, your root working directory would be: Project_folder

    from folder_x.A import A will work since path can be mapped from Project_folder

    in order for you to be able to use modules internally you need to use modules internal imports with relative path to Project_folder

    i.e. from folder_x.B import B and from folder_x.A import A

    Since you are mentioning that you are not allowed to change A.py or B.py

    only two possibilities you have:

    1. Move the file itself under Project_folder
    2. use sys.path.insert or sys.path.append to add your folder path folder_x to the system path.