Skip to content

Import files - Best practice

It is unbelievably annoying to do import in a python script.

Resource

Conclusion

  • Use absolute import if possible, unless the path is too long.
  • The entry point(which script will be executed) is critical

Example:

Let’s say we have below structure:

Untitled

We want to access CONST_A ,which is defined in utils/module_share.py, from package_a/module_a.py. However, we will execute project_level.py, which import module_a.py.

The main code is as below (note how the CONST_A is imported in different files)

# src_project/project_level.py
from package_a.module_a import CONST_A

print(" CONST_A is: ", CONST_A)

# src_project/package_a/module_a.py
from utils.module_share import CONST_A

# src_project/utils/module_share.py
CONST_A = "123123"

However, if we import project_level.py in root_level.py, the import path everywhere will just fail.

Comments