Set the sub-folders up as proper Python Packages
This method provides conformance with standard Python project packaging guidelines
I recommend a setup that makes the subfolders all proper python packages. To do that, add a blank __init__.py
file to each sub-folder with Python modules (i.e. files) in it.
With your original setup, ignoring the .vscode
folders:
src/
__init__.py
m1.py
lib/
__init__.py
m2.py
In this case, the imports would need to be from the src
folder (it would be considered a package itself, since it has a __init__.py
file in it):
import src.m1
import src.lib.m2
Make a proper scripts
packages
However, I recommend putting your scripts into their own package, not directly in the src
folder:
src/
scripts/
__init__.py
m1.py
lib/
__init__.py
m2.py
This allows all your packages to be referenced with a proper package name rather than src
like import scripts.m1
and import lib.m2
.
Side Notes
- If you want these packages to be "sub-packages", you can keep an
__init__.py
in the src folder to make it the root folder for everything.
- With that change, imports would be
import src.scripts.m1
and import src.lib.m2
.
- Python will go up in the parent folders until it finds a folder without an
__init__.py
file and then start the import statements in a chain from any sub-folders that are packages (i.e. have an __init__.py
file).
- Any folders chained together as packages after this process can be accessed locally without being added to the System or Python path.
How to import modules from the packages
Under this scheme, the m1.py
script should be able to import the m2.py
with something like the following. Since src
is not a package, it is the root from Python's perspective, and not included in import statements.
# In scripts.m1
import lib.m2 as m2
m2.function_1()
a = m2.function_2(m2.symbol_1)
or
from lib.m2 import function_1, function_2, symbol_1
function_1()
a = function_2(symbol_1)
If you add test files in this setup (say within a tests
directory inside of scripts
), then you can import the script functions as import scripts.m1 as m1
or from script.m1 import *
.
This setup makes the package conform to the standard for python packages and so if you want to make it installable or upload it to PyPi (or otherwise distribute it privately with zip files or through a git repo), you can define and build the project using the setuptools package using a standard setup.py
file. See Packaging Python Projects