1

Imagine a main.py. I have the following structure

├── main.py
├── moduleX
│   ├── setup.py
│   ├── submoduleA
│   │   └── fileA.py
│   │   └── fileB.py
│   ├── submoduleC
│   │   └── fileC.py

Main calls moduleX.setup and setup needs to call functions from submodules A and B.

However moduleX.setup is unable to find the submodules and I don't know how to import them

So it goes like this: in main.py

import moduleX.setup

in setup.py

from submoduleA import fileA
from submoduleA import fileB
import submoduleC

and all submodules and files are not found.

All subfolders have empty init.py files. I am not sure how to fill them, seems like a recursive problem.

I tried adding moduleX to sys.path I tried prpending moduleX everywhere I tried using .. and .

I don't know what I am doing wrong.

2
  • try adding this file into each sub-directory: __init__.py and fill the file like: from .fileC import * Commented May 29, 2020 at 11:26
  • thanks @Hanz . I have all subdirectories with __init__py files already Commented May 29, 2020 at 16:07

1 Answer 1

1

Python always uses the relative path to the file you are executing.

from moduleX.submoduleA import fileA
from moduleX.submoduleA import fileB
import moduleX.submoduleC

should work

Sign up to request clarification or add additional context in comments.

2 Comments

I ended up having to do weird things. But yes this was the first thing. I modified the init.py files to include import moduleX.submoduleA from moduleX.submoduleA import fileA and sometimes I need to calle fileA as submoduleA.submoduleA.fileA. very weird, but it worked. Thank you
A good way to approach the problem is by making each subdirectory a "lib". Create a init.py that includes all the files or classes you need, and based on this import you can access sub functions or classes. That is the way you are used to doing when importing numpy, pandas, ...

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.