pythonimportdirectorypython-importsys

How to import dependencies from other folder?


I have to folders A and B. In folder A is my main.py. In folder B there are a few classes in different scripts: B1.py, B2.py, B3.py…

I want to import a class from B1.py. I got that to work with sys.path.append and so on. But the problem is that the B1.py script imports other classes from the other scripts in folder B:

from B2 import classB2 from B3 import classB3

When I try to import ClassB1 in my main.py (which is in folder A) it can‘t import the classes classB2, classB3, etc. How do I fix that?

I tried to add B.B1 and B.B2 etc. in the B1.py,… documents. This works but I am supposed to not alter the code in B.


Solution

  • A tidy way to do this would be creating a package (Packaging python Projects) and then from the directory with the setup.py file in it running pip install. to install it on your local machine. This would allow you to import as you would with any installed module.

    For a quick and dirty solution you can add the path of the desired module's directory to the start of the sys.path variable in python and it will search there when looking to import.

    import statements in b1 wont be broken this way.

    Here is a test case in a folder A where each module in B imports the next and calls its hello function

    import sys
    
    sys.path.insert(1, '/root/projects/learning/B')
    
    import b1
    
    b1.hellob1()
    

    Here is the output

    # /bin/python3 /root/projects/learning/A/a1.py
    Hello World from b1.py
    Hello World from b2.py
    Hello World from b3.py