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 
⇐ Javascript: NodeList vs....Terminal Commands (CLI) for... ⇒
Image
Author of this website. I am passionate about programming and web design since the age of 12. After a stint in architecture and entrepreneurship, I came back to my original passion at 30 years old and became a self-taught web developer in less than 2 years.

Leave a Comment