1

I have a directory structure like this:

dir/
   frontend.py
   dir1/main.py
   dir2/backend.py
  • How do I import backend in main in Python?
  • How do I import frontend in main in Python?

Have tried all the answers on Stackoverflow. Nothing seems to work.

2
  • 1
    You need to have init.py file in dir1 and dir2 stackoverflow.com/questions/448271/what-is-init-py-for Commented Nov 28, 2017 at 11:19
  • I have done that too. Does not help me in importing modules from the parent directory. Commented Nov 28, 2017 at 11:33

2 Answers 2

1

In any folder from which you want to import source files you need to have existing init.py file.

I would advise structure like:

dir/
   main.py
   dir1/frontend.py
   dir1/__init__.py
   dir2/backend.py
   dir2/__init__.py

Then you import them in following fashion (in main.py):

import dir1.frontend
import dir2.backend
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks. I was aware of such a structure. I really wanted to know how to import modules from the parent directory and in the sub-directories within the parent directory. It's not possible always to structure the directories in the way that you have mentioned.
Thanks mate! But that did not help either. Tried adding my parent directory to PYTHONPATH also. Did not work for me. I cannot import modules from the parent directory.
As long as I run main.py from dir/ (like python ./dir1/main.py) I achieve proper results (both modules imported) with: import frontend, import dir2.backend. If it has to be run from dir1/ (python ./main.py) then I have no idea.
I've seen a "hacky" solution import all needed modules in the initial init.py of each subfolder, then the init.py of the main module would import each of those.
@jo9k I badly want to figure out the imports in Python. The structure you provided works fine always. I was aware of that. There should be a mechanism to import anything from anywhere and run from anywhere, I believe.
|
1

There is only one rule when it comes to importing files in a Python project.

You have to import the package relative to the directory from where the project is run.

For example in the question main.py should have something like this:

from dir.frontend import *
from dir.dir2.backend import *

But then you'll have to have something like main.py under dir/ which imports dir/dir1/main.py and then run python main.py.

So, try to keep the main.py always in the head directory so you don't have to worry about such a situation as above.

ONLY ONE RULE: Everything has to be imported relatively to the directory from where the project is run.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.