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
2
3
4
5
6
7
8
# file relative locations
# ...CWD/runing_scripts.py
# ...CWD/module_a.py
import module_a
```

## Module file not locates in CWD
If the module file are not locates in your CWD, then you must add the relative/absolute search path to your python compiler. You can achiever this via:

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
2
3
4
5
6
7

It is recommended to use relative path to import module rather than absolute path. Because sometimes you may need to sync your code on different PCs or share them with other people. You can not guarantee that your code absolute path is the same on all PCs.


# Module package
## How to create/declare a python module package
In python, you can put your python module .py files in a particular directory eg. In python 2. version, you need to create a '__init__.py' file in this direction. In python 3. version, you may not need to create this file. Then you can import this package and call any module and functions.

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
2
3

## Relative imports within the same module
For files locates in the same module packages, you can make relative imports not based on CWD but on the calling module file. For example, in module_a.py you wish to use module function within module_b11.py. Then you can write like this in module_a.py.

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.