How to fix Python ModuleNotFoundError — Ultimate guide (Pycharm)

chuuuing
3 min readFeb 10, 2022

--

Overview

There are 2 types of python module/package.

  • External packages: those you installed per pip install xxx
  • Internal packages: those you created by write class XXX():

Both packages directories need to be specified with the Environment Variable $PYTHONPATH !

External Packages

Answer the questions: which python are you using?

Check using terminal which python3. The result could look like this:

/Users/USERNAME/code/PROJECTNAME/venv/bin/python3

To ensure PyCharm can locate the packages, add the python directory into the ENV variable PYTHONPATH:

Edit configurations:

Edit Environment parameters:

Add venv-python directory to the end of existing value, separated with colon:
/user/local/lib/python3.9/site-packages:/Users/USERNAME/code/PROJECTNAME/venv/bin/python3

Usually your external packages are installed either locally or virtually(anaconda or venv), here are some examples:

  • local package directory: /usr/local/lib/python3.9/site-packages/
  • virtual package directory: /Users/USERNAME/opt/anaconda3/envs/ENVNAME/lib/python3.9/site-packages/
    /Users/USERNAME/Documents/workspace/PROJECTNAME/venv/lib/python3.9/site-packages/

⚠️ Requirement already satisfied

If you encounter Requirement already satisfied: PACAKGE NAME... /user/local/lib/python3.9/site-packages while /user/local/lib/python3.9/site-packages is NOT the python directory you are using, use --target=CORRECT_PYTHON_DIRECTORY to specify the destination. Example

pip install PACKAGE --target=/Users/USERNAME/Documents/workspace/PROJECTNAME/venv/lib/python3.9/site-packages/

⚠️ Everything installed but still ERROR

Solution: delete all packages under your lib/python3.9/site-packages/ and do the pip install -r requirements.txt --target='.../lib/python3.9/site-packages/' again.

Internal Packages

The problem is that python doesn’t know where to find your package.

SOLUTION

1. Open your projecg in PyCharm

2. Find the direct-parent-folder of your internal package.
In this case, the package we want to use is app , so the direct-parent-folder is src

3. Now set src as “Source Root”. You will see the folder color become blue.

>>> ⚠️ If the “Mark Directory as” is not an option in the right-click list. You can always go to Preferences | Project:<name> | Project Structure, and set the corresponding folder as source root.

4. Lets make sure python knows where to find packages — external and internal. PyCharm → Preferences → Build, Execution, Deployment → make sure you put the correct external-packages-directory in (A), and cross both checkboxes in (B) for internal-packages.

Hope this will solve your packages once for all. Remember, the error occurs ONLY when python doesn’t know where to look into! 🔍🔍🔍

--

--

chuuuing
chuuuing

No responses yet