Search code examples
pythonpython-import

How do I reduce repetitive imports from subfolders?


I am working on a large project in VSCode. I have various subfolders with plenty of .py files, and a main.py in the project root. I want to import various functions from various files that exist in different subfolders. I find from x import y a very redundant process. What is the efficient way to do it? How does a professional python developer do it?

my_project/
├── FolderA/
│   ├── __init__.py
│   └── module_a.py
├── FolderB/
│   ├── __init__.py
│   └── module_b.py
├── FolderC/
│   ├── __init__.py
│   └── module_c.py
├── __init__.py
└── main.py

Let's say the above is my structure and I want to call functions in main.py from module_a.py, module_b.py and module_c.py. Thanks.

I tried the following, but I can't keep doing it for 10/20 functions:

from FolderA.module_a import functionA
from FolderB.module_b import functionB
from FolderC.module_c import functionC

Also tried the following, it didn't work:

sys.path.append("D:\Python_workspace\software")

Solution

  • From a practical standpoint (if the folder representation you gave is accurate to your project) if you find yourself with lots of folders with one file each in them, you may want to reassess whether the categories/groupings you've chosen are realistic - too granular and you get a lot of the repetitive, snakey imports that you've shown. Unfortunately at that point with one file per folder there's not much you can do to solve your import problem short of restructuring the project tree.

    However, if your project is already in the following format (difference being multiple files in each subfolder):

    my_project/
    ├── FolderA/
    │   ├── __init__.py
    │   ├── module_a1.py
    │   └── module_a2.py
    ├── FolderB/
    │   ├── __init__.py
    │   ├── module_b1.py
    │   └── module_b2.py
    ├── FolderC/
    │   ├── __init__.py
    │   ├── module_c1.py
    │   └── module_c2.py
    ├── __init__.py
    └── main.py
    

    You can then set up imports in __init__.py (assume you're in FolderA/__init__.py):

    from module_a1 import fun1
    from module_a2 import fun2
    

    Then in any other file you can now just directly reference the directory/package and to grab what you've now indirectly imported:

    from FolderA import fun1, fun2