'How to programmatically add root folder to the path for every script?

The file structure I currently have is something like:

__init__.py
script_folder
    __init__.py
    s1.py
    s2.py
b_folder
    __init__.py
    b1.py
    b2.py
lib_folder
    __init__.py
    lib1.py
    libb2.py

Files in b_folder can use the files from lib_folder, and the scripts in script_folder can use the files from b_folder and lib_folder. I do imports as follows:

from lib_folder.lib1 import func_1

Imports from other folders seem to work if I add

import sys; sys.path.insert(0, '.') 

to every single file that does an import from another folder. Like this, it all works. But this repetitive line pollutes my code.

I wonder if there is a way to add the root folder to the path project-wide, or directory-wide, without having to add any magic line to every file that needs to import something from another folder?

Changing $PATH on my computer is not a good solution for me because the code is supposed to run on other machines.

I have tried to add import sys; sys.path.insert(0, '.') to all __init__.py, but it does not seem to make any difference.

My launch.json (in Visual Studio Code) is as below:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "args": ["-m"],
            "console": "integratedTerminal",
            "justMyCode": true
        }
    ]
}


Solution 1:[1]

Yes, there is a way and it is actually the canonical way of running python scripts. You must run the scripts as parts of the package they belong to from the root dir - so in your case remove the top level init py (the top folder is not a package), remove all the sys.path lines (this can lead to hair pulling bugs) and:

$ ls
lib_folder b_folder script_folder
$ python -m script_folder.b1 # note this is not a filesystem notation

Running this way python will add all your top level packages on the path and imports will function correctly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mr_and_Mrs_D