I’m trying to import functions located in a Python file outside of my Visual Studio Code workspace. Let’s say my structure is:
folder/
├── workspace/
│ └── main.py
│
└── python_scripts/
└── utils
└── __init__.py
└── functions.py
And let’s say from main.py I want to be able to call the list_files() function present in functions.py (of course I could put this file in my current workspace, but these are utility functions I want to share across many different projects). After (a lot!) of searching and tweaking, I was able to make it work using:
#main.py
sys.path.append('C:\folder\python_scripts')
from utils import *
list_files()
This script runs without any issues (inside __init__.py
there is also some code to add all functions from functions.py to the global name space). However, Visual Studio Code underlines the function list_files()
with a warning saying "list_files" is not defined.
Any idea why, and does it mean I messed up (again!) with the import process, even though the script runs?
2
Answers
I literally just did this the other day for the first time, on windows, here are the steps:
Search "env", choose "Edit the system environment variables"
next choose "Environment Variables"
under System variables, either edit or create PYTHONPATH
if you need to create it, the name = PYTHONPATH, the value = the path to your util folder:
you don’t need the line:
sys.path.append('C:\folder\python_scripts')
as (AFAIK) it essentially does the same thing but didn’t work for me.
Finally restart your IDE so that the code interpreter can reload.
:] happy importing util functions!
A relatively simple and effective solution is to add the following codes to your
settings.json
:This will guide Pylance to retrieve the folder.