In python, imports work only for files located in the calling file's directory. To be able to organize our files better, we need to use modules, but their import can be tricky. Here is how to import a child, sibling and parent module properly.
Import a module located in the same folder
Here is our file/folder structure:
root
|-- mod_a
| |-- __init__.py
| `-- file.py
`-- app.py
Files:
# app.py
import mod_a
# mod_a/__init__.py
from . import file
# mod_a/file.py
print('Hello world')
Result:
python3 app.py
# Hello world
Import a module located in a child folder
File/folder structure:
root
|-- mod_a
| |-- __init__.py
| `-- mod_b
| |-- __init__.py
| |-- file.py
`-- app.py
Files:
# app.py
import mod_a
# mod_a/__init__.py
from . import mod_b
# mod_b/__init__.py
from . import file
# mod_b/file.py
print('Hello world')
Result:
python3 app.py
# Hello world
Import a module located in a sibling folder
File/folder structure:
root
|-- mod_a
| |-- __init__.py
|-- mod_b
| |-- __init__.py
| |-- file.py
`-- app.py
|-- __init__.py
Files:
# __init__.py
from . import mod_a, mod_b
# app.py
import mod_a
# mod_a/__init__.py
import mod_b
# mod_b/__init__.py
from . import file
# mod_b/file.py
print('Hello world')
Result:
python3 app.py
# Hello world
Import a module located in a parent folder
File/folder structure:
root
|-- mod_a
| |-- __init__.py (optionnal)
| |-- file.py
| |-- mod_b
| |-- __init__.py
`-- app.py
Files:
# app.py
import mod_a.mod_b
# mod_a/mod_b/__init__.py
from mod_a import file
# mod_a/file.py
print('Hello world')
# mod_a/__init__.py
from . import mod_b
Result:
python3 app.py
# Hello world