VS code: Updated PYTHONPATH in settings. Import autocomplete now works, but module not found when running program

Question:

I have been trying to fix a problem while running python files in VSCode. I have a directory with a program my_program.py that imports a module personal_functions.py from a folder packages_i_made.

project
├── .env
└── folder_a
    ├── my_program.py

my_packages
├── __init__.py
└── packages_i_made
    ├── __init__.py
    └── personal_functions.py
     

my_program.py contains:

from packages_i_made import personal_functions as pf

When typing this import line, the text autocompletes. Previously autocomplete didn’t work and imports failed with the module not being recognized, which is why I added the .env file which contains PYTHONPATH="C:/Users/user_1/my_packages" . I also updated the workspace settings with a path to the .env file.

I hoped this would fix my import issue, but imports still fail as before when running the file:

Traceback (most recent call last):
  File "c:Usersuser_1......projectfolder_amy_program.py", line 1, in <module>
    from packages_i_made import personal_functions as pf
ModuleNotFoundError: No module named 'packages_i_made'

I’m an utter beginner to programming, but my interpretation of the issue is this: As far as I can tell, Pylance can see the my_packages directory and recognize the packages inside it. However, the python interpreter fails to recognize the path to my_packages. If it’s important, the my_packages directory is in my system path. I’ve been banging my head against this for days. Any help is appreciated.

Asked By: h4zard

||

Answers:

Open the vscode from your project root folder. It should work then.

Answered By: Ashin Shakya

The easiest way to solve the problem is to use the sys.path.append method above your import statement to indicate the path. For you, the code should look like this:

import sys
sys.path.append("C:/Users/user_1/my_packages")

from packages_i_made import personal_functions as pf

You set the .env file just to let vscode intellisense (pylance for python) see the package, but in fact the python interpreter still cannot access your package. This effect is the same as adding "python.analysis.extraPaths" configuration in settings.json, it will add additional import search resolution path.

The difference this brings is that when you write import code you get autocompletion and the yellow warning squiggly line disappears. But when you run the code, you still get errors because the python interpreter doesn’t actually have access to your package.

VS code uses the currently open folder as the workspace. So which folder you open in vscode is also critical.

Answered By: JialeDu