Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save gmp-prem/7e5e06d3e466a0eb14ef7ca2740765da to your computer and use it in GitHub Desktop.

Select an option

Save gmp-prem/7e5e06d3e466a0eb14ef7ca2740765da to your computer and use it in GitHub Desktop.
Python 101
If you have a code structure like this
root_dir
script_dir
env.py
util_dir
commons.py
image_proc.py
main.py
If you happen to work with python script named env.py and want to import the 2 modules from util_dir,
and when you import, it shows the error like this.
====================================================
from utils.commons import CommonFuctions
ModuleNotFoundError: No module named 'utils'
====================================================
This is because when you run the script in script env.py directory, the python interpreter sys.path will make
the current path as a current at index 0, this makes when you want to import the module from other directory impossible
TO FIX THIS PROBLEM,
1. create a script named __init__.py in the util_dir and inside the file, write this code
====================================================
from util_dir.commons import COMMONS
from util_dir.image_proc import IMAGEPROC
====================================================
2. at the env.py file in the script_dir directory, before importing modules from util_dir folder, write this
====================================================
import sys
import os
PROJECT_ROOT = os.path.abspath(os.path.join(
os.path.dirname(__file__),
os.pardir)
)
sys.path.append(PROJECT_ROOT)
from util_dir.commons import COMMONS
from util_dir.image_proc import IMAGEPROC
====================================================
This should fix the problem above.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment