I have the following directory structure:
.
├── main.py
└── subfolder1
├── file1.py # def hello(): print("hello")
├── __init__.py
└── subfolder2
├── file2.py # def world(): print("world")
└── __init__.py
I'm trying to be to access functions from both subfolder1/file.1py
and subfolder/subfolder2/file2.py
.
I have an empty __init__.py
in each nested folder as per the documentation I could find. I'm assuming that's necessary. (Update: I've just now removed the __init__.py
's from both subfolders and it still works. I thought having this was necessary?)
Contents of main.py
:
import subfolder1.file1
import subfolder1.subfolder2.file2
subfolder1.file1.hello()
subfolder1.subfolder2.file2.world()
When I execute main.py
, both functions are called correctly. But the syntax is more cumbersome than I'd like, I don't want to have to repeatedly specify directory paths in subsequent imports.
I've tried doing something like
import subfolder1 as sub1
import sub1.subfolder2 as sub2
sub1.file1.hello()
sub2.file2.world()
But my IDE's Pylance alerts me that Import "sub1.subfolder2" could not be resolved
and the terminal outputs on execution
Traceback (most recent call last):
File "/home/me/project/main.py", line 2, in <module>
import sub1.subfolder2 as sub2
ModuleNotFoundError: No module named 'sub1'
I've seen online the sys.append('/path/to/subfolder')
method, but I don't like having to take up a line of code before every multi-nested import. It defeats the purpose, as my goal is to avoid repeatedly typing out paths, whether in the import
statement or a sys.append()
method.
Are there any ways to do multi-level modularization more elgantly/succintly in Python?