In programming, sometimes we need to make define our own function modules for further usage. Thus we should import/declare there user defined modules in our current script. In Matlab, we do this by addpath() function, in Python, we need to make proper imports or to convert our modules as packages. Here we give a brief introduction on how to make proper imports of external modules in python 3 version.
Direct imports
Module file locates in Current Working Directory (CWD)
Suppose the module .py file locates in your CWD directory, then you can direction import the module as:
1 | # file relative locations |
file relative locations
.dir1/CWD/runing_scripts.py
.dir1/CWD/module_a.py
.dir2/module_b.py
import sys
sys.path.append(’…/dir2/’)
from dir2 import module_b
1 |
|
file relative locations
…/package_dir/init.py
…/package_dir/module_a.py
…/package_dir/module_b.py
…/package_dir/sub_dir1/module_a1.py
…/package_dir/sub_dir1/subsub_dir12/module_b11.py
import sys
sys.path.append(’…/’)
from package_dir import module_a
from package_dir.sub_dir1 import module_a1
from package_dir.sub_dir1.subsub_dir12 import module_b11
1 |
|
code for imports in module_a.py
from .sub_dir1/subsub_dir12 import module_b11
## Import external module outside current package
Currently, I haven't find a correct way to relative import external module files outside a module. The temporary solution is to copy the external module file inside the current package. In the future, when I find useful solution, I will update this part.